Can anyone please tell if both the entity - i.e.
2-D array char array[][9]
and
array of pointers char *array[9]
are same or different??

- 1
- 1
- 4
-
4They are different, you say "2d array" and array of pointers. Don't you notice that you are implicitly saying that they are different. – Iharob Al Asimi Jul 17 '17 at 14:00
-
`char array[9][1]` is roughly the same as `char *array[9]`, except for the memory allocation. The former is static, the latter requires dynamic allocation or pointer re-assignment. – Serge Jul 17 '17 at 14:04
-
yes, i got the difference. Thanks guys. – Vikere Jul 17 '17 at 18:40
1 Answers
They are different.
The most prominent difference is that in the case of the array the elements will be laid out contigously in memory but in the case of the array of pointers they will not.
To be able to use the elements of the array of pointers, you need to make them point to some valid memory, you can do that either by using malloc()
or by pointing to an array for example. In both cases the elements of the potential array the pointer points to are not contiguous.
Your confusion might be due to the fact that arrays can be syntactically used as pointers, because if you pass an array to a function expecting a pointer then, it is equivalent to a pointer that points to the first element of such array.
Also,
int x[3] = {1, 2, 3};
int *y = x;
is valid and you can use y
as if it was an array even though it's not. It's a pointer, and you can use it to traverse the elements of the array x
using pointer arithmetic.
One way of expressing such arithmetic is by the use of the []
syntax, in fact
int value = y[1]
is equivalent to performing a pointer arithmetic operation on y
and dereferencing it, exactly equivalent to
int value = *(y + 1);
i.e. move to the element that is (1×sizeof *y
) bytes after the beginning of y
and get the value there.

- 52,653
- 6
- 59
- 97