簡體   English   中英

使用malloc的指針到指針分段錯誤

[英]Pointer to Pointer Segmentation Fault with malloc

我在函數中使用了Pointer to Pointer,但這不是一個2d數組,它只是一個字符串。 我嘗試了各種組合,但仍然無法使用,這是如何工作的?

int get_next_line(const int fd, char **line)
{
    char buffer[BUFF_SIZE];
    int i;

    i = 0;
    *line = malloc(sizeof(char *) * BUFF_SIZE);
    read(fd, buffer, BUFF_SIZE);
    while (buffer[i] != '\n')
    {
    if(!(*line[i] = (char)malloc(sizeof(char))))
        return (0);
        *line[i] = buffer[i];
        i++;
    }
    write(1, buffer, BUFF_SIZE);
    printf("%s", *line);
    return (0);
}

int main()
{
    int fd = open("test", O_RDONLY);
    if (fd == -1) // did the file open?
        return 0;
    char *line;
    line = 0;
    get_next_line(fd, &line);
}
There is an error in a way you are trying to print the string. 

* line是指向指針數組的指針。 該數組中的每個指針將存儲一個character元素。 *行將無法打印您存儲的字符串。

Hence use the below code to get the expected results:    

int get_next_line(const int fd, char **line)
    {
        char buffer[BUFF_SIZE];
        int i;

        i = 0;
        *line = malloc(sizeof(char) * BUFF_SIZE);
         if (*line == NULL)
         return 0;        
         read(fd, buffer, BUFF_SIZE);
        while (buffer[i] != '\n')
        {
            *line[i] = buffer[i];
            i++;
        }
        write(1, buffer, BUFF_SIZE);
        printf("%s", *line);
        return (0);
    }

int main()
{
    int fd = open("test", O_RDONLY);
    if (fd == -1) // did the file open?
        return 0;
    char *line;
    line = 0;
    get_next_line(fd, &line);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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