What are 2D Char Array vs Pointer Array- C Programming Course in Telugu

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Free Embedded C Course • Strings • Lecture 25

2D Char Array vs Pointer Array

A clear side-by-side comparison of a two-dimensional char array and an array of pointers to strings, with valid and invalid operations proven by real compiler output. Part of our free C programming course.

Students in every free c programming course mix up char names[3][12] and const char *names[3]. They look similar, print similarly, and then one of them crashes the program. This lecture of our free embedded C course puts both side by side so you know which operations are legal, which are undefined, and which layout suits embedded C programming on small RAM.

What You Will Learn

  • The exact memory layout of a 2-D char array and of a pointer array
  • Which assignments and library calls are valid for each one
  • Why an uninitialised pointer slot crashes strcpy and scanf
  • How to read the compiler messages that warn you
  • How to choose between the two for firmware tables

Prerequisites

You should have finished the previous lecture on arrays of pointers to strings, and know what strcpy does from the string function lectures.

Two Declarations, Two Different Machines

char        grid[3][12];   /* 3 rows x 12 bytes, characters live inside */
const char *ptrs[3];       /* 3 pointers, characters live somewhere else */
grid[3][12] : characters stored inside the array
grid[0] sensor\0?????
grid[1] motor\0??????
grid[2] relay\0??????
ptrs[3] : three addresses, text stored separately
ptrs[0] → sensor\0
ptrs[1] → motor\0
ptrs[2] → relay\0

The question marks in the first diagram are unused bytes. Each row must be as wide as the longest string you will ever store, so short names waste space. The pointer table wastes nothing inside itself, but each pointer costs 4 or 8 bytes.

Build and Run the Comparison

Save this as compare_tables.c:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char        grid[3][12];
    const char *ptrs[3];

    strcpy(grid[0], "sensor");
    strcpy(grid[1], "motor");
    strcpy(grid[2], "relay");

    ptrs[0] = "sensor";
    ptrs[1] = "motor";
    ptrs[2] = "relay";

    printf("grid : %zu bytes of table\n", sizeof grid);
    printf("ptrs : %zu bytes of table (literal bytes live elsewhere)\n", sizeof ptrs);

    grid[1][0] = 'M';              /* our own array: safe to edit */
    printf("grid[1] = %s\n", grid[1]);
    printf("ptrs[1] = %s\n", ptrs[1]);
    return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o compare_tables compare_tables.c
./compare_tables

Output on a 64-bit Linux PC:

grid : 36 bytes of table
ptrs : 24 bytes of table (literal bytes live elsewhere)
grid[1] = Motor
ptrs[1] = motor

The grid costs 3 times 12 equals 36 bytes no matter how short the names are. The pointer table costs 3 times 8 equals 24 bytes plus 7 + 6 + 6 bytes of literal text, so on this tiny example the totals are similar. With long, uneven strings, or on a 32-bit microcontroller where a pointer is 4 bytes, the pointer table usually wins clearly.

Valid and Invalid Operations

Operationchar grid[3][12]const char *ptrs[3]
Assign a literal: x[0] = "abc";Invalid, compile errorValid
strcpy(x[1], "abc"); right after the declarationValidUndefined behaviour, slot points nowhere
scanf("%s", x[2]); right after the declarationValid if input fits in 12 bytesUndefined behaviour
Change one character: x[0][0] = 'S';ValidInvalid for literals (read-only memory)
Point a slot to another stringNot possibleValid
Swap two entriesCopy 12 bytes three timesSwap two pointers

Proof 1: assigning to a grid row

#include <stdio.h>

int main(void)
{
    char grid[3][12];

    grid[0] = "sensor";   /* cannot assign to an array */
    printf("%s\n", grid[0]);
    return 0;
}
gcc -std=c11 -Wall -o bad1 bad1.c
bad1.c: In function 'main':
bad1.c:7:13: error: assignment to expression with array type
    7 |     grid[0] = "sensor";   /* cannot assign to an array */
      |             ^

The compiler refuses because grid[0] is an array of 12 chars, not a pointer variable. Use strcpy to copy text into it.

Proof 2: copying into an unset pointer slot

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *ptrs[3];

    strcpy(ptrs[1], "motor");   /* ptrs[1] points nowhere valid */
    printf("%s\n", ptrs[1]);
    return 0;
}
gcc -std=c11 -Wall -O2 -o bad2 bad2.c
bad2.c: In function 'main':
bad2.c:8:5: warning: 'ptrs' is used uninitialized [-Wuninitialized]
    8 |     strcpy(ptrs[1], "motor");   /* ptrs[1] points nowhere valid */
      |     ^~~~~~~~~~~~~~~~~~~~~~~~
bad2.c:6:11: note: 'ptrs' declared here
    6 |     char *ptrs[3];

This time it only warns, and only with optimisation on. A program that compiles can still crash. Never run it: strcpy would write to whatever random address sits in ptrs[1].

Same bug with scanf. scanf("%s", ptrs[2]); on an unset slot has the same problem. A pointer slot must point to real, writable memory before any function writes through it.

Making a Pointer Slot Writable

There are three safe ways to give a slot real storage:

  1. Point it to a literal and only read it (use const char *)
  2. Point it to a writable char buffer you own, such as char buf0[16]; ptrs[0] = buf0;
  3. Allocate memory with malloc, which is the topic of the next lecture
Which one should I pick?
Fixed text, read only → const char *table[]
Edit text in place, known max length → char grid[N][LEN]
Unknown lengths, sort cheaply → pointer array + malloc

Embedded Considerations

  • RAM: a static const char *const table can be placed in flash by the linker, using almost no RAM
  • Determinism: a grid has a fixed size known at compile time, which some safety standards prefer to malloc
  • Speed: swapping pointers copies 4 bytes, swapping grid rows copies the whole row
  • Security: a grid row is a fixed buffer, so always bound copies with the row size

Common Mistakes

Forgetting the terminator slot. A grid row of 12 holds at most 11 visible characters plus '\0'. A 12-character name overflows into the next row.

Believing the two print the same size. sizeof grid counts all characters, sizeof ptrs counts only pointers.

Best Practices

  • Initialise every pointer: with a literal, a buffer, or NULL
  • Compile with -Wall -Wextra and treat warnings as defects
  • Use strncpy or snprintf when filling grid rows from outside data
  • Prefer the pointer table for constant text and the grid for editable text

Try It Yourself: Three Quick Experiments

  1. Measure the waste. Change the grid to char grid[3][40] and rerun the demo. The grid jumps to 120 bytes while the pointer table stays at 24. Short names in wide rows are the most common way students waste RAM.
  2. Print the row gap. Print (void *)grid[1] - (void *)grid[0] using a cast to char * first. You will get 12, the row width, which proves the rows are packed with no pointers between them.
  3. Overflow on purpose in a safe test. Compile a copy of the program with -fsanitize=address -g, copy a 14 character name into grid[0], and read the report. It names the exact line, which is the quickest way to learn what a row overflow looks like.

These small experiments take five minutes and make the table layout stick far better than reading alone. Keep your results, because the interview questions at the end of this chapter section ask about exactly these sizes.

Summary and Key Takeaways

  • A 2-D char array owns its characters, a pointer array owns only addresses
  • Assignment works on pointer slots, copying works on grid rows
  • Unset pointer slots must never be written through
  • The compiler catches the grid mistake with an error, but the pointer mistake only with a warning

With this comparison clear, the next lecture of the free embedded C course shows how to give each pointer slot exactly the memory it needs using malloc.

Frequently Asked Questions

What is the difference between char arr[5][10] and char *arr[5]?

The first stores 50 characters inside the array. The second stores 5 pointers and the characters live elsewhere.

Why does grid[0] = “text” fail?

Because grid[0] is an array. C cannot assign whole arrays, so use strcpy.

Why does strcpy on an uninitialised pointer crash?

The pointer holds a random address, so strcpy writes to memory you do not own.

Which one uses less RAM?

A const pointer table in flash usually uses the least RAM. A grid wastes the unused bytes of every row.

Can I change a character of a string literal through a pointer?

No. That is undefined behaviour and often faults on embedded targets.

Is this covered in a free embedded systems course?

Yes, it is a standard topic in embedded C programming because every firmware project has text tables.

Keep Learning Embedded C for Free

Continue this free c tutorial with dynamic strings using malloc.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →