What are the differences between an array of char pointers and a 2D array?
char* pasz[3] = {"abc", "def", "ghi"};
char asz[3][] = {"abc", "def", "ghi"};
The similarities and differences are basically the same as between these two:
char *psz = "jkl";
char sz[] = "jkl";
The first is originally read-only.
psz[0] = 'a'; // Illegal!!
The second, you can modify, since you allocate it with the []
.
sz[0] = 'b';
// sz == "bkl"
The first, you can modify what it points to:
char mysz[] = "abc";
psz = mysz;
psz[0] = 'b';
// mysz == "bbc"
The second, you cannot:
sz = mysz; // Can't assign an array to an array!!
Array of arrays (aka multi-dimensional array) looks like (in memory):
a[0][0], a[0][1], a[0][n-1], a[1][0], a[1][1], ..., a[1][n-1], ..., a[m-1][n-1]
array of pointers looks like:
p[0], p[1], ..., p[m-1]
where each slot is a pointer and can point to whatever. If they all happen to point to arrays with n
elements each, then p[i][j]
and a[i][j]
can be used similarly in expressions, but they're actually quite different objects.
char* my_string[];
represents an array of strings.
int my_grid_of_ints[][];
char my_block_of_text[][];
If color = byte[3]
then you could represent your screen monitor
color my_pixel_buffer[][] = new color[768][1024];
is a 2D array. As you can see, a 2D array can represent anything, including an array of char pointers (such as multiple lines of strings).
You can access elements with the same syntax, but the guarantees about memory layout is much different. The 2d array is contiguous. The array of pointers is not.