【问题标题】:Using snprintf to fill struct使用 snprintf 填充结构
【发布时间】:2017-08-26 19:39:49
【问题描述】:

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

【问题讨论】:

  • 了解struct person 的实际定义方式可能会有所帮助。
  • 难道firstname 只是一个转储指针?
  • 而且这看起来更像 C,而不是 C++。请决定,这是两种不同的语言。

标签: c++ c struct printf


【解决方案1】:

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

data[i - 1].firstname = buffor;

你需要这样的东西:

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

【讨论】:

  • "您需要为每个结构分配内存" 实际上 OP 正是这样做的。 ;-)
  • @alk。好吧,那是错字。更正:-)
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 2011-08-13
  • 2012-08-14
  • 2015-04-27
  • 1970-01-01
相关资源
最近更新 更多