【发布时间】:2020-07-14 20:33:33
【问题描述】:
所以我正在做一些事情,但我遇到了一个大问题。在我的程序中,当我输入小数组大小时,我没有任何问题并且程序运行良好(例如 3x3)。当我用 6x6 (i=6, j=6) 之类的东西输入 X 数组时,我得到了这个错误,我真的不知道为什么......我从昨天开始尝试解决它,但仍然没有:(任何人都可以帮忙我?我在我的电脑上使用的软件是 ubuntu 18.04,如果这很重要的话。我会感谢任何人提供帮助。
我的代码是这样的:
#include <stdlib.h>
int main(int argc, char *argv[])
{
int N,M; // N=megethos rows , M=megethos columns
int **X,**Y; // pinakas
int size,i,j,num;
int freqamount, sizeOfArray;
float freq;
printf("\n\nGive me the rows of the table: ");
scanf("%d",&N);
printf("\n\nGive me the columns: ");
scanf("%d",&M);
size = N*sizeof(int);
X = malloc(size);
size = M * sizeof(int);
for(i=0; i<M;i++){
X[i] =(int*)malloc(size);
}
Y = malloc(size);
for(i=0;i<3;i++){
Y[i] = (int*)malloc(3*sizeof(int));
}
printf("\n\nGive the number ");
scanf("%d",&num);
printf("\n\ngive the frequence");
scanf("%f",&freq);
sizeOfArray = N*M;
freqamount =(int) ((freq * sizeOfArray)/100);
printf("\nIt should appear: %d times\n",freqamount);
/*
if(freqamount == 100){
X[i][j] = num;
}
if(freqamount == 0){
x[i][j] != num;
}
X[i][j] = rand() % 100;
*/
for(i=0;i<N;i++){
for(j=0;j<M;j++){
X[i][j] = num;
}
}
for(i=0;i<N;i++){
for(j=0;j<3;j++){
if(j=0){
Y[i][j] = rand() % 100;
}
if (j=1){
Y[i][j] = i;
}
if(j=2){
Y[i][j] = j;
}
}
printf("%d\t",Y[i][j]);
}
for(i=0;i<N;i++){
free(X[i]);
}
free(X);
return 0;
}
【问题讨论】:
-
您尝试过什么解决问题的方法? How to Ask
-
这与你的问题无关。尝试将代码减少到仍然存在您正在谈论的问题的最小大小。 Step through it with a debugger 以查看您是否能够识别出无法正常工作的特定部分,等等。
-
size = N*sizeof(int); X = malloc(size);错误,您应该将N的指针 数量分配给int,即N * sizeof(int *)。 -
size = M * sizeof(int);是正确的,但for(i=0; i<M;i++)之后的循环是错误的,因为您循环的是M而不是N。 -
` if(j=0){` 不会做你想做的事,你需要一个
==。带有警告的编译器应该会告诉你(比如gcc -Wall...)