开发者

Confused Results: Array of pointers in C

I wrote a little piece 开发者_StackOverflowof 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


You have set pstr[0], pstr[1] and pstr[2] to equal p. And the last thing written into p is the byte sequence "good". So at the end, you are essentially printing p three times.


All three pointers in the pstr array point to the same memory location (p).

And since you modify the contents of that memory location a few times using the strcpy calls, it will contain whatever was placed there last.

In this case, the string "good" was placed there last, so that's what all three pointers in the pstr array will point to, and that's what will get displayed repeatedly in the loop.


Fundamental point - the array of memory referenced by p can only contain one string at a time.

The loop at the end of your code will always print out the same value on each iteration, since you seeded each entry in the array pstr with the same pointer p.

If you want to see different results on each iteration, you have to point pstr[0], pstr[1] and pstr[2] to different areas of memory.


pstr[0], pstr[1], and pstr[2] all point to the same 10-character array p. When you copy each string, you change the contents of the array p, but it's address doesn't change. So, after you copied the last string into p, you just end up printing the same thing three times.


not only all the entries of the array are p, but you are strcpy'ing non zero terminated strings. strcpy() needs the strings to be zero terminated or you'll get a buffer overrun with unpredictable consequences.


Simple, you set pstr[i]=p; bit p is the address of a static buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜