Hi there,
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.