小编Yiw*_*wei的帖子

困惑的结果:C中的指针数组

我写了一小段代码来测试指针数组是否按预期工作.然后我得到了这个有线结果 - 在第三个指针赋值之后,指针数组都指向最后一个字符串.谁能解释发生了什么?谢谢.

#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]);
}
Run Code Online (Sandbox Code Playgroud)

该程序的输出是:

morning
hello
good
good
good
good
Run Code Online (Sandbox Code Playgroud)

c arrays pointers

2
推荐指数
1
解决办法
180
查看次数

标签 统计

arrays ×1

c ×1

pointers ×1