开发者

Dynamic Multidimensional Arrays

开发者 https://www.devze.com 2023-03-17 19:47 出处:网络
I tried everything and from what I understood, this code is correct but it still gives my Segmentation Fault. Help?

I tried everything and from what I understood, this code is correct but it still gives my Segmentation Fault. Help?

#include <stdio.h>
#include<malloc.h>

void da(int ***array, int row, int col){
    int i;
    *array=(int **)malloc(sizeof(int *)*row);
    for (i=0; i<row; i++)
        *array[i]=(int *)malloc(sizeof(int)*col);   
}

main(){
    int **array;
    int i,n,m;
 开发者_运维技巧   printf("Input number of rows: ");
    scanf("%d",&n);
    printf("Input number of columns: ");
    scanf("%d",&m);
    da(&array,n,m);
    for (i=0; i<n; i++)
        free(array[i]);
    free(array);
}


Operator [] has more priority than operator *. Put brackets on: (*array)[i]=(int *)malloc(sizeof(int)*col);


The code seems OK. My guess is that one of the mallocs is failing (return NULL) since you are not checking the response. The the free on NULL obviously fails. This could be a matter of memory left. What numbers for rows and columns are you using?

Other advice. This code is overcomplicated. Since you are creating a regular matrix, it is simpler and more efficient to create a single dimension array.

void da(int **array, int row, int col){
    int i;
    *array=(int *)malloc(sizeof(int)*row*col);
    return; }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号