簡體   English   中英

結構指針中的字符串數組

[英]Array of string in a struct pointer

我有以下結構:

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不為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
}

該文件為/ etc / passwd,我想讀取該文件的第一行,並將其存儲到struct records行[i]的位置。

我也試過這個:

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

在GDB中parse_file()范圍內:

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

如何解決此錯誤?

您缺少分配步驟; 對於每個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 );
}

您需要為每行分配內存,然后才能將數據復制到其中:

  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM