c - 结构指针中的字符串数组

标签 c string pointers struct malloc

我有以下结构:

strcut records
{
    char **lines;
    int count;
}

有一个函数get_pwent(),相关代码如下:

struct records *passwd = malloc(sizeof(strcut records));
passwd->lines = malloc(sizeof(char *) * MAX_STR_SIZE);

通过一些 malloc 错误检查(passwd 不为空,passwd->lines 不为空)它被传递到我的 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
}

该文件是/etc/passwd,我想读取该文件的第一行并将其存储到 struct records lines[i] 位置。

我也试过这个:

fgets(record->lines[i], ...) //which also gets a seg fault.

在 GDB 中,在 parse_file() 范围内:

(gdb) p record
$1 = {struct records *} 0x602250

我该如何修复这个错误?

最佳答案

你需要为每一行分配内存,然后才能将数据复制到它:

  record->line[i] = malloc(MAX_STR_SIZE+1);    // allocate memory first.
  fgets((*record).lines[i], MAX_STR_SIZE, in); // <-- Segment fault here

关于c - 结构指针中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26389573/

相关文章:

php - 如何使用php分解字符串,去除多余字符

C:指针和数组

c - 556以下的C程序输出如何?请解释一下 char *b=(char *)&a;

c++ - 指针递增和递减

c 指针 双指针

c++ - 在您的 dll 项目中包含外部 DLL 依赖项吗?

c - 传递数组时在C中的函数参数中强制数组大小

c - C 库上的十进制到二进制

java - 如何在java中将字符串UTF-8转换为ANSI?

vb.net - 如何禁用 VS2015 中的自动字符串检测?