Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Arrays and Pointers - C

Tags:

arrays

c

pointers

Just trying to really get my head round Arrays and Pointers in C and the differences between them and am having some trouble with 2d arrays.

For the normal 1D array this is what I have learned:

char arr[] = "String constant";

creates an array of chars and the variable arr will always represent the memory created when it was initialized.

char *arr = "String constant";

creates a pointer to char which is currently pointing at the first index of the char array "String constant". The pointer could point somewhere else later.

char *point_arr[] = {
    "one", "two","three", "four"
};

creates an array of pointers which then point to the char arrays "one, "two" etc.

My Question

If we can use both:

char *arr = "constant";

and

char arr[] = "constant";

then why can't I use:

char **pointer_arr = {
    "one", "two", "three", "four"
};

instead of

char *pointer_arr[] = {
    "one", "two", "three", "four"
};

If I try the char ** thing then I get an error like "excess elements in scalar initializer". I can make the char** example work by specifically allocating memory using calloc, but as I didn't have to do this with char *arr = "blah";. I don't see why it is necessary and so I don't really understand the difference between:

char **arr_pointer;

and

char *arr_pointer[];

Many thanks in advance for your advice.

like image 557
Joe Avatar asked Jul 30 '26 22:07

Joe


1 Answers

See this answer in the C FAQ:

There it is explained for char [] vs char *. The same thing can be extended to char *[] vs char **.

like image 174
George Avatar answered Aug 01 '26 13:08

George



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!