【发布时间】:2016-11-05 03:58:36
【问题描述】:
我有这个代码:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char **string = malloc(sizeof(char) * 20);
FILE *fp = fopen("input.txt", "r");
fscanf(fp, "%s", *string);
printf("%s\n", *string);
}
此代码生成分段错误。但是,如果我将 **string 更改为单个字符指针并将 *strings 更改为 string 它可以工作。为什么是这样?以及如何将 fscanf 与指针数组一起使用?
谢谢。
【问题讨论】:
-
简答:你使用 malloc 错误
-
你想要一个字符串数组吗?就像
string[0]是一个字符串,而string[0][0]是一个字符?您需要为数组 char** 做一个 malloc,然后为每个字符串 char* 做一个 malloc。 -
明白了。谢谢。