gpt4 book ai didi

c - 使用 scanf 的二维数组中的段错误

转载 作者:行者123 更新时间:2023-11-30 16:08:37 25 4
gpt4 key购买 nike

在这段代码中,我在 scanf 查找棋盘值的部分遇到了段错误。一开始,我扫描了两次尺寸。

#include <stdio.h>
#include <stdlib.h>
#include "maxsum.h"
int main() {
int x,y,n,m,**board;
scanf("%d %d",&n,&m);
board=malloc(n*sizeof(int));
if (board==NULL) {
printf("Unable to allocate memory \n");
return 1;
}
for (x=0;x<n;x++) {
*(board+x)=malloc(m*sizeof(int));
if (*(board+x)==NULL) {
printf("Unable to allocate memory \n");
return 1;
}
}
for (x=0;x<n;x++) {
for (y=0;y<m;y++) {
scanf("%d",&board[x][y]); // the error happens in this line ,and only when variable x is about to become n-1 when n>4 (very confused as to why)//
}
}
printf("%d \n",Solve(n,m,board)); //not relevant //
return 0;
}

最佳答案

您没有分配正确的内存量:

board=malloc(n*sizeof(int));

您将 board 设置为 int * 数组,但仅为 int 数组分配空间。您系统上的 int 很可能小于 int *,因此您分配的空间不够。随后您将写入超出分配内存的末尾,导致 undefined behavior .

将此分配更改为:

board=malloc(n*sizeof(int *));

或者更好:

board=malloc(n*sizeof(*board));

关于c - 使用 scanf 的二维数组中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293037/

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