jah*_*han 2 c arrays malloc segmentation-fault
我在这里问了我的问题C中最大的2-D数组大小以及在得到声明之前我得到的答案是有些人重复的,我修改了我的代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,n,m,p = 0 ;
int sum[100000] = {0};
scanf("%d%d%d",&n,&m,&p);
/*for ( i = 0 ; i < n ; i++ )
{
for( j = 0 ; j < m ; j++ )
{
a[i][j] = j + 1 ;
}
}*/
int **a = (int **) malloc(sizeof(int)*n);
for(i=0; i<n; i++)
{
a[i] = (int *) malloc(sizeof(int)*m);
for(i=0; i<n; i++){
for(j=0; j<m; j++){
a[i][j] = j + 1 ;
}
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但我仍然得到相同的分段错误.请帮我修复它,我希望这个问题不会被声明为重复.:P
你讲malloc()错了大小.
这个:
int **a = (int **) malloc(sizeof(int)*n);
Run Code Online (Sandbox Code Playgroud)
应该:
int **a = malloc(n * sizeof *a);
Run Code Online (Sandbox Code Playgroud)
不要强制转换结果malloc(),并使用sizeof返回指针指向的类型,即int *可能与int系统上的大小不同.
因此,因此:
a[i] = (int *) malloc(sizeof(int)*m);
Run Code Online (Sandbox Code Playgroud)
应该:
a[i] = malloc(m * sizeof *a[i]);
Run Code Online (Sandbox Code Playgroud)
在依赖指针有效之前malloc(),添加代码以确保所有成功,即永不返回NULL.另外,还要确保初始scanf()回报率3,并打印出的值n,m和p.也删除sum.