【发布时间】:2012-12-30 05:39:36
【问题描述】:
我想读取一个文件并将每一行写入 char 数组。由于我不知道行数,因此我认为最有效的方法是使用 char 指针的二维数组。但是我遇到了分段错误。
我的问题可能与这个问题重复: 2D array of char pointers --> Segmentation fault?
但我想不出 C 的正确语法,所以无法尝试。
这是我的代码:
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
char **new_line;
int i = 0;
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
strcpy(new_line[i], line);
i++;
}
【问题讨论】:
-
你没有为
new_line分配任何内存
标签: c pointers char segmentation-fault