使用snprintf填充struct

时间:2017-04-01 16:20:31

标签: c++ c struct printf

有人能告诉我为什么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;
}

1 个答案:

答案 0 :(得分:0)

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

data[i - 1].firstname = buffor;

你需要这样的东西:

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