1

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);
}
2
  • Where does it segfault? What have you tried so far to fix it? Commented Jul 7, 2011 at 15:04
  • Don't cast the return value of malloc. Casting is, at best, redundant and (as in your code) may hide errors; namely the failure to include the header where malloc is declared making the compiler assume the return type is int instead of void*. Commented Jul 7, 2011 at 15:14

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.