1

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.

1
  • Where precisely are you getting the segfault? Can you post the console output you get from this code? Commented May 31, 2013 at 16:38

1 Answer 1

2
*(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]);
Sign up to request clarification or add additional context in comments.

1 Comment

what is arr? how's it different from &arr[0][0] or arr[0]?

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.