C++ 使用snprintf填充结构

C++ 使用snprintf填充结构,c++,c,struct,printf,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 inti=1; char Buffer[100]; int n=3; 结构人*数据; 数据=(结构人*)malloc(n*sizeof(结构人)); while(i您需

有人能告诉我为什么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
inti=1;
char Buffer[100];
int n=3;
结构人*数据;
数据=(结构人*)malloc(n*sizeof(结构人));

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

data[i - 1].firstname = buffor;
你需要这样的东西:

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

了解
struct person
的实际定义可能会有所帮助。可能是
firstname
只是一个转储指针吗?而且这看起来更像C,而不是C++。请确定,这是两种不同的语言。“你需要为每个结构分配内存”事实上OP就是这样做的。-@alk。好吧,那是打字错误。更正:-)
data[i - 1].firstname = (char*)malloc(strlen(buffor) + 1);
strcpy(data[i - 1].firstname, buffor);