有人可以告诉我为什么struct中的变量会被覆盖吗?

输出为:

Buffor is: 1.name , struct is: 1.name
Buffor is: 2.name , struct is: 2.name
Buffor is: 3.name , struct is: 3.name
3.name
3.name
3.name




    int i = 1;
    char buffor[100];
    int n = 3;

    struct person * data;
    data = (struct person *) malloc(n * sizeof(struct person));

    while (i <= n) {
        snprintf(buffor, sizeof(buffor), "%d.name", i);
        data[i - 1].firstname =buffor;
        printf("Buffor is: %s , struct is: %s \n", buffor, data[i - 1].firstname);
        i++;
    }

    for (int i = 0; i < n; i++) {
        printf("%s \n", data[i].firstname);
    }
    return 0;
}

最佳答案

您需要为每个结构的firstname属性分配内存。复制字符串只会复制指针。代替

data[i - 1].firstname = buffor;


您需要这样的东西:

data[i - 1].firstname = (char*)malloc(strlen(buffor) + 1);
strcpy(data[i - 1].firstname, buffor);

09-29 21:41