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
If you really want to get through the bottom of it then try to understand arrays and pointers through ints rather than chars. According to my experience I had trouble understanding pointers and arrays when chars were involved. Once you understand ints properly you will realize that it's not diff at all.
int *ptr[] is an array of pointers to integers where as int **ptr is a pointer to a pointer that references an integer.
int *arrptrs[2];
arrptrs[0]=(int *)malloc(sizeof(int)*5);
arrptrs[1]=(int *)malloc(sizeof(int)5);
This initializes two arrays referenced by the elements of the array arrptrs. The name of an array refers to the memory location of the first element of an array so arrptrs is of type (int *) as the first element of this array is of type (int *)
Suppose we do int **ptr=arrptrs Then, *ptr is the first element of arrptrs which is arrptrs[0]and *(ptr+1) is arrptrs[1] and doing a *arrptrs[0] is the first element in the array referenced by arrptrs[0].
I hope this helps although I am not sure if you needed this.
Pointers (char *pointer;
) have values; arrays (char array[];
) have elements.
The declaration char **ptr2
declares an object that can take a single value, not an object that can take several elements.
In short, you cannot use { ... }
as an initialiser for a scalar.
char **arr_pointer
declares a scalar, not an array. In contrast, the reason you can do char *arr = "constant";
is because you're still declaring a scalar, it just happens to point at a string literal.
Quote from Wikipedia:
In computing, a scalar variable or field is one that can hold only one value at a time... ...For example, char, int, float, and double are the most common scalar data types in the C programming language.
So as Oli Charlesworth pointed out in his reply using {.....} initializes multiple items but as char **arr_pointer is a 'scalar' and so can only point at 1 thing at a time (an address) then the {...} notation cannot work here.
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 **
.