at the moment, I’m trying some pointer stuff in C. But now, I have a problem with a pointer array. By using my code below, I get a strange output. I think there is a big mistake in the code, but I can’t find it.
I just want to print the strings of the pointer array.
#include <stdio.h>
int main(void)
{
char *words[] = {"word1", "word2", "word3"};
char *ptr;
int i = 0;
ptr = words[0];
while(*ptr != '\0')
{
printf("%s", *(words+i));
ptr++;
i++;
}
return 0;
}
Output: word1word2word3Hã}¯Hɡ
Thanks for helping.
initially,
ptrpoints to the'w'in"word1". So the loop iterates five times until*ptr == '\0'. But the arraywordscontains only three elements, thus the fourth and fifth iteration invoke undefined behaviour and garbage is printed when the bytes after thewordsarray are interpreted as pointers to 0-terminated strings. It could easily crash, and if you try it on other systems, with other compilers or compiler settings, it will sometimes crash.You could translate the loop to
to see more easily what it does.
If you want to print out the strings in the
wordsarray, you can useAs
wordsis an actual array, you can obtain the number of elements it contains usingsizeof. Then you loop as many times as the array has elements.