gpt4 book ai didi

c - 段错误(核心已转储)c

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

我的代码贴在下面,我很确定段错误发生在 main() 底部的 while 循环中。

我的程序必须读取一个文件,数据以网格形式存在,fscanf 获取网格的维度,然后创建具有这些维度的二维数组,然后我使用 while 循环逐行遍历并然后一个 for 循环逐个字符遍历该行中的字符,将其存储在数组的内部,然后 i++ 将其存储在二维数组的下一层。

谁能告诉我为什么要这样做?

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>

char direction;
int steps;
int cur[2];
char** gridArray;
int* move(int cur[2]);
int* getCommand(int next[2], char** gridArray);
char** make2DFileArray(int sizeX, int sizeY);
int* makeArray(int size);

int main(int argc, char *argv[] )
{
FILE *fp;
int rows;
int columns;
int i=0,j;
char line[1000];

if ((argc < 2)^(argc > 3)) {
fprintf(stderr, "Usage: thebox mapfile [maxsteps]\n");
exit(1);
}
if( argc < 3 ) { steps = 10; }
else { steps = argv[2]; }

fp = fopen(argv[1], "r");
if( fp == NULL) {
fprintf(stderr, "Missing map file.\n");
exit(1);
}

fscanf(fp, "%d %d", &rows, &columns);
gridArray = make2DFileArray(rows+1, columns);

while ( fgets(line, 1000, fp) != NULL) {
for(j=0; j < columns - 1; j++) {
gridArray[i][j] = line [j];
}
i++;
printf("%s", line);
}
fclose(fp);
printf("(sidepos)>\n");
return 0;
}

还有我的辅助方法,就是这个

char** make2DFileArray(int sizeX, int sizeY)
{
int i;
char** array;
array = (char**) malloc(sizeX*sizeof(char*));

for (i = 0; i < sizeX; i++) {
array[i] = (char*) malloc(sizeY*sizeof(char));
return array;
}
return array;
}

int* makeArray(int size)
{
int* array;
array = (int*) malloc(size*sizeof(int));
return array;
}

最佳答案

错误在 make2DFileArray 函数中。您只需在循环中第一次分配后返回,这意味着只会分配 gridArray[0]

由于不会分配任何其他条目,因此访问例如gridArray[1] 是未定义的行为,也是导致崩溃的原因。

关于c - 段错误(核心已转储)c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18224676/

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