I wrote a little piece of code to test whether the array of pointer is working as I expected. Then I got this wired results -- After the third pointer assignment, the array of pointer all point to the last string. Anyone can explain what happened? Thank you.
#include <string.h>
#include <stdio.h>
main() {
char *pstr[10];
char p[10];
char *s1 = "morning";
char s2[10] = {'h','e','l','l','o'};
char s3[10] = {'g','o','o','d'};
int i = 0;
strcpy(p, s1);
pstr[0] = p;
printf("%s\n", pstr[0]);
strcpy(p, s2);
pstr[1] = p;
printf("%s\n", pstr[1]);
strcpy(p, s3);
pstr[2] = p;
printf("%s\n", pstr[2]);
for (i = 0; i < 3; i++)
printf("%s\n", pstr[i]);
}
The output from the program is:
morning
hello
good
good
good
good
int a;, here a is uninitialized. We do not know what it contains.char[10] a;Same here. We don't know what is in a[0] through a[9]. However, withchar a[10] = {'x'};, thenais initialized. a[0] will containx. But, since a[1] through a[9] was not mentioned in the initalizer, they get their default value of 0.