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)?
In the first example, it is a jagged array I suppose.
It declares an array of const pointers to a char. So the string literal can be as long as you like. The length of the string is independent of the array columns.
In the second one.. the number of characters per row (
string
) lengths must be 9 as specified by your column size, or less.No, only 3 pointer are allocated and they point to 3 string literals.
and
are not at all equivalent. First is an array of 3 pointers whereas the second is a 2D array.
For the first only pointer are allocated and the string literals they point to may be stored in the read-only section. The second is allocated on automatic storage (usually stack).
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).
Is not a multidimensional array! It is simply an array of pointers.
The number of characters plus a null terminator. Same as any string literal.
I think you want this:
Here, 10 is the amount of space per string and all the strings are in contiguous memory. Thus, there will be padding for strings less than size 10.