Pictures can help — ASCII Art is fun (but laborious).
char *stuff[] = {"hello","pie","deadbeef"};
+----------+ +---------+
| stuff[0] |--------->| hello |
+----------+ +---------+ +-------+
| stuff[1] |-------------------------->| pie |
+----------+ +------------+ +-------+
| stuff[2] |--------->| deadbeef |
+----------+ +------------+
The memory allocated for the 1D array of pointers is contiguous, but there is no guarantee that the pointers held in the array point to contiguous sections of memory (which is why the pointer lines are different lengths).
char stuff[3][9];
strcpy(stuff[0], "hello");
strcpy(stuff[1], "pie");
strcpy(stuff[2], "deadbeef");
+---+---+---+---+---+---+---+---+---+
| h | e | l | l | o | | x | x | x |
+---+---+---+---+---+---+---+---+---+
| p | i | e | | x | x | x | x | x |
+---+---+---+---+---+---+---+---+---+
| d | e | a | d | b | e | e | f | |
+---+---+---+---+---+---+---+---+---+
The memory allocated for the 2D array is contiguous. The x's denote uninitialized bytes. Note that stuff[0]
is a pointer to the 'h' of 'hello', stuff[1]
is a pointer to the 'p' of 'pie', and stuff[2]
is a pointer to the first 'd' of 'deadbeef' (and stuff[3]
is a non-dereferenceable pointer to the byte beyond the null byte after 'deadbeef').
The pictures are quite, quite different.
Note that you could have written either of these:
char stuff[3][9] = { "hello", "pie", "deadbeef" };
char stuff[][9] = { "hello", "pie", "deadbeef" };
and you would have the same memory layout as shown in the 2D array diagram (except that the x's would be zeroed).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…