gpt4 book ai didi

c - 数独布局与 malloc 崩溃

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

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

void *mymalloc(size_t size){
void *x=malloc(size);
if(x==NULL){
printf("Not enought memory for you!\n");
exit(1);}
else return x;
}

int main(){
int m , n , **A , i , j , z ,k;
printf("Give rows: \n");
scanf("%d" , &n);
printf("Enter columns: \n");
scanf("%d" , &m);
A=(int**)mymalloc(n*sizeof(int));
for(i=0;i<n;i++){
A[i]=(int*)mymalloc(m*sizeof(int));
}
printf("Give your sudoku: \n");
for(k=0;k<m;k++){
for(z=0;z<n;z++){
for(i=0;i<n;i++){
printf(" %d: " , i);
for(j=0;j<m;j++){
printf("%d" , A[i][j]=j);
}
printf(" ");
}
printf("\n");
}
printf(" \n");
}
}

当“n”(行)小于 4 时,此程序将 printf 设置为具有“n”行和“m”列的数独布局。但是当行数超过 4 时,程序就会崩溃。

最佳答案

主要问题:内存分配不正确:(@Kerrek SB)
sizeof(int) 可能不是 sizeof(int*)

的 saem 大小
 //  A=(int**)mymalloc(n*sizeof(int));
A=(int**)mymalloc(n*sizeof(int*));

为了避免这种错误,推荐这种风格,不易出错,更容易维护。

A = mymalloc(n * sizeof *A); 

其他小问题:

// printf("Not enought (spelling)
printf("Not enough ...

// int main() { // Invalid signature
int main(void) {

// No need for cast
// A[i] = (int*) mymalloc(...
A[i] = (int*) mymalloc(...

return 0; // missing main() return value

关于c - 数独布局与 malloc 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27203258/

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