Dineshkumar
Dineshkumar

Reputation: 4245

Segmentation fault: Dynamic memory allocation for multidimensional array in C

I tried to create a multidimensional array dynamically in C but I am getting a segmentation fault!

int **arr=malloc(sizeof(int*) *row);
printf("&ar:r%d arr:%d %d\n\n",*arr,arr,arr[0]);
for(i=0;i<row;i++){
    *(arr+i)=malloc(sizeof(int)*col);
    printf("row: %d",arr[i]);
}
printf("\nbase arr: %d",&arr[0][0]);

I checked out address of row and allocated memory as required for total elements in column. But still when I access it arr[i][j] it shows different address [That's why sigsegv].

for(i=0;i<row;i++){
    for(j=0;j<col;j++){
        arr[i][j]=0; //this point
    }
    puts("done");
}

AFAIK, somearr and &somearr is same for 1 dimensional array. Here it gives arr[0] and *arr address of row 0. but what is arr? why is it different?

[I checked other related questions in Stack Overflow but I don't have those problems and can't solve this still.]

Any references or links to study the concept will be great.

Upvotes: 1

Views: 233

Answers (1)

John Kugelman
John Kugelman

Reputation: 361564

*(arr+row)=malloc(sizeof(int)*col);
printf("row: %d",arr[row]);

Trying to access *(arr+row) inside the for loop is the cause of your segfault. Valid indices are from 0 to row-1. I'm guessing you meant to use i rather than row.

*(arr+i)=malloc(sizeof(int)*col);
printf("row: %d",arr[i]);

Upvotes: 2

Related Questions