[英]Segmentation fault(core dumped) C
I am trying to make an X[N][M] array with malloc, and I am having this error.我正在尝试使用 malloc 创建一个 X[N][M] 数组,但出现此错误。 Can anybody help me with that ?
有人可以帮我吗?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char argv[])
{
int N,M; // N=megethos rows , M=megethos columns
int **X; // pinakas
int size,i,j;
printf("Give me the rows of the table: ");
scanf("%d",&N);
printf("Give me the columns: ");
scanf("%d",&M);
size = N*sizeof(int*);
X = malloc(size);
size = M * sizeof(int*);
for(i=0; i<N;i++){
X =malloc(size);
}
for(i=0;i<N;i++){
for(j=0;j<M;j++){
printf("Eisagwgh toy %d - %d stoixeioy: ",i+1,j+1);
scanf("%d",&X[i][j]);
}
}
for(i=0;i<N;i++){
printf("\n");
for(j=0;j<M;j++){
printf("%d",X[i][j]);
}
}
free(X);
}
I have already try to change this line: size = N*sizeof(int*);
我已经尝试改变这一行:
size = N*sizeof(int*);
to this: size = N*sizeof(int);
对此:
size = N*sizeof(int);
but still same error appear.但仍然出现相同的错误。
Please see the below code, I just made a very small change in your code, must see the comment.请看下面的代码,我只是对你的代码做了一个很小的改动,必须看注释。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char argv[])
{
int N,M; // N=megethos rows , M=megethos columns
int **X; // pinakas
int size,i,j;
printf("Give me the rows of the table: ");
scanf("%d",&N);
printf("Give me the columns: ");
scanf("%d",&M);
size = N*sizeof(int*);
X = malloc(size);
size = M * sizeof(int*);
for(i=0; i<N;i++){
//Here it intialize each row with size
X[i] =malloc(size);
}
for(i=0;i<N;i++){
for(j=0;j<M;j++){
printf("Eisagwgh toy %d - %d stoixeioy: ",i+1,j+1);
scanf("%d",&X[i][j]);
}
}
for(i=0;i<N;i++){
printf("\n");
for(j=0;j<M;j++){
printf("%d",X[i][j]);
}
}
free(X);
}
I suggest this way of allocating memory:我建议这种分配内存的方式:
X = malloc(N * sizeof(int*));
for (int i = 0; i < N; i++)
X[i] = (int*)malloc(M * sizeof(int));
instead of this wrong allocating:而不是这种错误的分配:
size = N*sizeof(int*);
X = malloc(size);
size = M * sizeof(int*);
for(i=0; i<N;i++){
X =malloc(size);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.