我在为包含 char* 的结构数组分配内存时遇到问题。
我有一个结构“人”
typedef struct
{
char *name;
char *surname;
char *phonenumber;
} Person;
我想要做的是从文件中读取一些数据并填充我必须动态分配内存的人的数组( Person *array )。
目前,我有这样的事情:
array = malloc(sizeof(Person) * arraysize);
Person *buff;
char text[100];
char *result;
for(i=0; i<arraysize; i++)
{
buff = &array[i];
fgets(text, 100, f );
//Read first name
result = strtok(text,":");
buff->name= malloc(strlen(result));
buff->name= result;
//Read surname
result = strtok(0,":");
buff->surname = malloc(strlen(result));
buff->surname = result;
//Read phone number
result = strtok(0, ":");
buff->phonenumber = malloc(strlen(result));
buff->phonenumber = result;
}
当我打印出整个数组时,我没有得到任何有效数据。我想知道我做错了什么。我提前感谢您的回答!