I’m trying to write a C99 program and I have an array of strings implicitly defined as such:
char *stuff[] = {"hello","pie","deadbeef"};
Since the array dimensions are not defined, how much memory is allocated for each string? Are all strings allocated the same amount of elements as the largest string in the definition? For example, would this following code be equivalent to the implicit definition above:
char stuff[3][9];
strcpy(stuff[0], "hello");
strcpy(stuff[1], "pie");
strcpy(stuff[2], "deadbeef");
Or is each string allocated just the amount of memory it needs at the time of definition (i.e. stuff[0] holds an array of 6 elements, stuff[1] holds an array of 4 elements, and stuff[2] holds an array of 9 elements)?
Pictures can help — ASCII Art is fun (but laborious).
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).
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’, andstuff[2]is a pointer to the first ‘d’ of ‘deadbeef’ (andstuff[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:
and you would have the same memory layout as shown in the 2D array diagram (except that the x’s would be zeroed).