I am confused about the following line of code:
char* words[] = { "aaa", "bbbb", "ccccc", "dddddd" };
The way I understand, each word is first stored and then each position of the array words will point then to the first character of each word. How are these strings stored? Is there dynamic allocation going on here or are these words stored on the stack?
If they are stored on the stack, in which way are they stored? For instance, if I print some of the contents of words as below:
#include <stdio.h>
int main () {
char* words[] = { "aaa", "bbbb", "ccccc", "dddddd" };
printf("\n\n(*words)[0] = %s", words[0]);
printf("\n\n(*words)[0]+1 = %s", words[0]+1);
return 0;
}
instead of printing aaa and bbbb, what I get is aaa and aa. I do not really understand what is the reason for this since, the way I see it, words[0]+1 should point to the string bbbb and not to the second character of aaa. What is going on here?
No.
words[0]is a char pointer itself – it’s perfectly fine that you get the second character of “aaa” by adding one to it. What you want iswords + 1or&words[0] + 1which will correctly be “bbbb”.Also, the strings themselves are allocated upon launching the executable and they’re probably put in the data or bss section of the binary by the linker. Also, when you declare and initialize
words, it’ll be allocated on the stack as any other automatic array and its items will be assigned to pointers to the beginning of each string constant.