【发布时间】:2020-11-26 00:07:50
【问题描述】:
我是 C 的初学者。我想从二维数组中获取每列所有元素的总和,然后放入另一个单维数组。当编译器尝试这样做时,它会给出错误。
#include<stdio.h>
#include<stdlib.h>
int** allocArrayMatrix ( int nl, int nc);
void showArrayMatrix(int ** a, int nl, int nc);
void formArray(int ** a, int nl, int nc);
int SumArray(int ** a, int nl, int nc);
void freeMemoryArray(int** a, int nl);
int main() {
int **a, nl=10, nc=10;
int f;
int *p;
a = allocArrayMatrix(nl, nc);
if (a == NULL) {
puts("Memoria p/u tabloul 2-D nu a fost alocata");
}
else {
puts("Memoria a fost alocata cu succes");
}
formArray(a,nl,nc);
printf("\nTablul bidimensional format:\n ");
showArrayMatrix(a,nl,nc);
p = SumArray(a, nl,nc );
for (f=0;f<nc;f++){
printf("%d\t",*(p+f));
}
freeMemoryArray(a,nl);
}
int ** allocArrayMatrix( int nl, int nc) {
int i;
int** a=(int **)malloc(nl*sizeof (int*));
if (a==NULL) return a;
for (i=0; i<nl ;i++)
{a[i] =(int*)malloc(nc*sizeof(int));
if (a[i]==NULL) return NULL;
}
return a;
}
void showArrayMatrix(int ** a, int nl, int nc)
{
int i,j;
for (i=0;i<nl;i++){
for (j=0;j<nc;j++) {
printf ("%d\t", a[i][j] );}
printf("\n"); }
return;
}
void formArray(int ** a, int nl, int nc)
{
int i,j;
for (i=0;i<nl;i++){
for (j=0;j<nc;j++)
a[i][j] = rand()%100-50 ;
}
return;
}
int SumArray(int ** a, int nl, int nc)
{int i,j, Sum;
static int b[10];
for (i=0; i<nc; i++){
Sum = 0;
for (j=0;j<nl;j++){
Sum = Sum + a[j][i];
}
b[i] = Sum;
}
return b;
}
void freeMemoryArray(int** a, int nl) {
int i,j;
for (i = 0; i < nl; i++) {
free(a[i]);
}
free(a);
}
那是输出
Memoria a fost alocata cu succes
Tablul bidimensional format:
33 36 27 -35 43 -15 36 42 -1 -29
12 -23 40 9 13 -24 -10 -24 22 -14
-39 18 17 -21 32 -20 12 -27 17 -15
-21 -48 -28 8 19 17 43 6 -39 -8
-21 23 -29 -31 34 -13 48 -26 -35 20
-37 -24 41 30 6 23 12 20 46 31
-45 -25 34 -23 -14 -45 -4 -21 -37 7
-26 45 32 -5 -36 17 -16 14 -7 0
37 -42 26 28 38 34 -47 1 4 49
-18 10 26 18 -11 -38 -24 36 44 -11
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
问题出在哪里?我发现这是由于内存分配不正确,但我无法解决这个问题
【问题讨论】:
-
请查看第 34 行和第 95 行有关不同间接级别的编译器警告。
-
旁白:你正在调用
rand(),所以当你越过调试阶段时,我建议你把srand(time(NULL))放在main()的开头,只调用一次。不过目前,该计划课程是可重复的。
标签: c