[英]Array of string in a struct pointer
I have a following struct: 我有以下结构:
strcut records
{
char **lines;
int count;
}
There is a function get_pwent()
which the concerning code is like this: 有一个函数
get_pwent()
,相关代码如下:
struct records *passwd = malloc(sizeof(strcut records));
passwd->lines = malloc(sizeof(char *) * MAX_STR_SIZE);
With a few malloc error checking ( passwd
is not null, passwd->lines
is not null) it's passed down to my parse_file()
: 通过一些malloc错误检查(
passwd
不为null, passwd->lines
不为null),将其传递给我的parse_file()
:
parse_file(struct records *record, FILE * in)
{
int i = 0;
... // a while loop
fgets((*record).lines[i], MAX_STR_SIZE, in); // <-- Segment fault here
i++;
... // end while
}
The file is /etc/passwd and I want to read in the first line of this file and store that into the struct records lines[i] position. 该文件为/ etc / passwd,我想读取该文件的第一行,并将其存储到struct records行[i]的位置。
I also tried this: 我也试过这个:
fgets(record->lines[i], ...) //which also gets a seg fault.
in GDB, under parse_file()
scope: 在GDB中
parse_file()
范围内:
(gdb) p record
$1 = {struct records *} 0x602250
How can I fix this error? 如何解决此错误?
You're missing an allocation step; 您缺少分配步骤; for each
passwd->lines[i]
, you need to do another allocation: 对于每个
passwd->lines[i]
,您需要进行另一次分配:
// Allocate space for array of pointers
passwd->lines = malloc( sizeof *passwd->lines * max_number_of_strings );
for ( size_t i = 0; i < max_number_of_strings; i++ )
{
// Allocate space for each string
passwd->lines[i] = malloc( sizeof *passwd->lines[i] * max_string_length );
}
You need to allocate memory for each line before you can copy data to it: 您需要为每行分配内存,然后才能将数据复制到其中:
record->line[i] = malloc(MAX_STR_SIZE+1); // allocate memory first.
fgets((*record).lines[i], MAX_STR_SIZE, in); // <-- Segment fault here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.