我有一个由几个字符串组成的动态结构数组,例如 char *str1
、char *str2
、char *str3
。
我必须从文件中获取字符串,并根据字符串长度为每个结构成员分配内存。
我该如何处理这个问题? 非常感谢。
最佳答案
“动态结构数组”是什么意思?它是一个结构体数组还是一个字符串数组(=char 指针数组)?
如果它只是一个指针数组,您只需为每个条目调用 malloc(),然后分配字符串即可。
char *strings[5];
void insert_string(int array_index, char *string, int length)
{
strings[array_index] = malloc(length);
strcpy(strings[array_index], string, length);
}
当然,您必须添加代码以防止数组溢出,或自动跟踪索引...
关于c - 从文件中的字符串获取字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49208360/