Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char **name VS char *name[]

I know this topic was already discussed several times and I think I basically know the difference between arrays and pointer but I am interested in how arrays are exactly stored in mem.

for example:

const char **name = {{'a',0},{'b',0},{'c',0},0};
printf("Char: %c\n", name[0][0]); // This does not work

but if its declared like this:

const char *name[] = {"a","b","c"};
printf("Char: %c\n", name[0][0]); // Works well

everything works out fine.

like image 936
Quick n Dirty Avatar asked Dec 10 '25 13:12

Quick n Dirty


1 Answers

When you define a variable like

char const*  str = "abc";
char const** name = &str;

it looks something like this:

+---+     +---+    +---+---+---+---+
| *-+---->| *-+--->| a | b | c | 0 |
+---+     +---+    +---+---+---+---+

When you define a variable using the form

char const* name[] = { "a", "b", "c" };

You have an array of pointers. This looks something like that:

          +---+     +---+---+
          | *-+---->| a | 0 |
          +---+     +---+---+
          | *-+---->| b | 0 |
          +---+     +---+---+
          | *-+---->| c | 0 |
          +---+     +---+---+

What may be confusing is that when you pass this array somewhere, it decays into a pointer and you got this:

+---+     +---+     +---+---+
| *-+---->| *-+---->| a | 0 |
+---+     +---+     +---+---+
          | *-+---->| b | 0 |
          +---+     +---+---+
          | *-+---->| c | 0 |
          +---+     +---+---+

That is, you get a pointer to the first element of the array. Incrementing this pointer moves on to the next element of the array.

like image 107
Dietmar Kühl Avatar answered Dec 12 '25 06:12

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!