[英]C Allocating memory for array of structures containing multiple char*
我在为包含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;
}
当我打印出整个数组时,我没有得到任何有效的数据。 我想知道我在做什么错。 我预先感谢您的回答!
buff->name= result
复位指针buff->name
为指向相同的位置在存储器中作为result
。 如果要复制result
的字符串内容,请使用strcpy
:
strcpy(buff->name, result);
但是请注意,在调用malloc
,还必须为尾随的NUL字符保留空间:
buff->name = malloc(strlen(result) + 1);
如果您使用的是POSIX系统(Linux,Mac OS X和任何Unix),则可以使用更方便的strdup
替换malloc
, strlen
和strcpy
:
buff->name = strdup(result);
问题是:
result = strtok(text,":");
buff->name= malloc(strlen(result));
buff->name= result;
您需要使用strcpy进行复制,并且malloc分配的字符串的长度应比字符串长度大一以容纳NUL char。
buff->name= malloc(strlen(result) + 1);
这个:
buff->name= malloc(strlen(result));
buff->name= result;
被打破。 您不能像在C中那样分配“字符串”,您需要复制字符。 malloc()
返回的指针被result
覆盖, result
内存泄漏。 另外,您需要为终止符留出空间。
因此,应为:
buff->name= malloc(strlen(result) + 1);
strcpy(buff->name, result);
strtok
每次都会覆盖指针。 因此,随着迭代的进行,您会丢失指向数据的指针。
如果您希望直接分配指针,则可以执行以下操作:
result = strtok(text,":");
buff->name= strdup(result);
strdup是POSIX函数。 因此,如果它不可用,您可以轻松地实现它。
您需要将结果文本复制到新分配的内存块中。 现在您只需分配内存(将指针分配给指针),然后丢弃该指针并为其分配新的指针结果。 您需要将结果压缩到新的内存分配中。 另外strlen不包含终止的零字节,因此新存储块中没有足够的空间。 有一个功能strdup可以满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.