gpt4 book ai didi

c - 从输入文件读取数组时出现段错误(核心转储)错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:32 25 4
gpt4 key购买 nike

我正在尝试通过 C 中的输入文件读取数组。显示数组后出现段错误(核心转储)错误。谁能解决这个问题。这是我的c程序

#include <stdio.h>
#include<stdlib.h>
int main()
{
int c, i, j, row, col, nl, cr,nt;
col = nl = cr = nt=0;
int k;
row=1;
FILE *fp = fopen("IO.txt", "r");
// Figure out how many rows and columns the text file has
while ((c = getc(fp)) != EOF)
{
if (c == '\n')
nl++;
if (c == '\r')
cr++;
if(c=='\t')
nt++;
col++;
if (c == '\n')
row++;
putchar(c);
}
//row=row+1;
col = (col - (nl + cr+nt));
col = (int) (col/row);
char **array = malloc(sizeof(char *) * row);

for(int k=0;k<row;k++)
{
array[c] = malloc(sizeof(char) * col);
}

if(fp)
{
for( ;; )
{
c = getc(fp);
if ( c == EOF )
{
break;
}
if ( c != '\n' && c != '\r' )
{
array[i][j] = c;
if ( ++j >= col )
{
j = 0;
if ( ++i >= row )
{
break;
}
}
}
}
fclose(fp);
}
for ( i = 0; i < row; i++ )
{
for ( j = 0; j < col; j++ )
{
putchar( array[i][j]);
}
putchar('\n');
}
free(array);
array=NULL;
return 0;
}

这是我的输入文件

IO.txt

 0  0   0   0   0   0   0

0 0 1 0 2 0 0

0 1 0 4 3 6 0

0 0 4 0 0 5 0

0 2 3 0 0 7 8

0 0 0 0 8 0 9

0 0 0 0 8 9 0

最佳答案

在这段代码中:

for(int k=0;k<row;k++){
array[c] = malloc(sizeof(char) * col);
}

你应该使用 k , 不是 c访问 array . c完全是另一个变量。

你的编译器应该已经警告过你了。始终注意警告:

io.c: In function ‘main’:io.c:7:9: warning: unused variable ‘k’ [-Wunused-variable]     int k;         ^

Also, sizeof(char) is explictly 1, so you never need to specify it.

So the loop should look like this:

for(int k=0;k<row;k++){
array[k] = malloc(col);
}

此外,您忘记释放 array 的元素在你有空之前array本身。你应该这样做:

for (int k=0; k<row; k++){
free(array[k]);
}

此外,您没有正确计算列数。这段代码:

if(c=='\t')
nt++;
col++;

将增加 col每次通过循环,因为col++不属于 if(c=='\t') .你需要牙套:

if (c =='\t') {
nt++;
col++;
}

另外,您忘记了关闭然后重新打开您的文件,或者在您第二次阅读它之前返回到开头。 if(fp)不会为你做任何事。你应该这样做:

/* Close and then reopen the file */
fclose(fp);
fp = fopen(fopen("IO.txt", "r"));

或者这个:

/* Seek to the beginning of the file */
fseek(fp, 0, SEEK_SET);

还有,你忘了初始化 ij0 .编译器不会为你做,所以你需要:

int c, i = 0, j = 0, row, col, nl, cr, nt;

此外,您没有正确计算列数或行数。按回车来统计行数不太靠谱,因为文件最后一行可能没有回车,但假设有,初始化row0 ,则列计算为:

col = (col / row) + 1;

此外,您在第二次阅读文件时忘记检查标签。将字符添加到数组的条件应该是:

if ( c != '\n' && c != '\r' && c != '\t')

这就是所有的逻辑问题。剩下的只是卫生和风格:检查文件是否成功打开,检查 malloc() 的结果等

关于c - 从输入文件读取数组时出现段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42311404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com