【发布时间】:2017-01-29 20:38:07
【问题描述】:
我在编译时没有收到任何错误。当我运行它时,程序就会崩溃。我尝试直接从 generate 函数打印矩阵,它打印了第一行和第二行。
这是我的代码
void generate(int **a)//*Function to generate a matrix a[i][j]=i+j*
{
int i,j;
for(i=0;i<5;i++){
for(j=0;j<4;j++){
a[i][j]=i+j;
}
}
}
void print(int **a)//*print the resulting matrix from generate function*
{
int i,j;
for(i=0;i<5;i++){
for(j=0;j<4;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
}
int main()
{
int *a=(int*)malloc(5*4*sizeof(int));//*allocating memory for a matrix of 4 lines and 5 columns.*
generate(&a);
print(&a);
}
【问题讨论】:
-
您的函数不知道有哪些行和列。他们不会仅仅因为您希望他们收到 2 星指针。检查编译器警告。
-
指向指针 (
&a) 的指针与二维数组不同。
标签: c pointers memory crash malloc