[英]Pointer to Pointer Segmentation Fault with malloc
I'm using a Pointer to Pointer in my function, but it's not a 2d Array, it's just one string. 我在函数中使用了Pointer to Pointer,但这不是一个2d数组,它只是一个字符串。 I tried all kinds of combinations and still can't get it to work, how does this work?
我尝试了各种组合,但仍然无法使用,这是如何工作的?
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.
The *line is a pointer to array of pointers. * line是指向指针数组的指针。 each pointer in that array will store a character element.
该数组中的每个指针将存储一个character元素。 The *line will not be able to print your stored string.
*行将无法打印您存储的字符串。
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.