easymoneysnapper
easymoneysnapper

Reputation: 21

Dynamically allocating space for a 2D array

I am a novice C programmer trying to write a function that dynamically allocates space for a 2D array. I am getting a segmentation fault when running this code & i'm not sure why.

#include <stdio.h>
#include <stdlib.h>

int allocate_space_2D_array(int **arr, int r, int c) {
        int i,j;

    arr = malloc(sizeof(int *) * r);
    for (i = 0; i < r; i++)
            arr[i] = malloc(sizeof(int *) * c);

    for (i = 0; i < r; i++) {
            for (j = 0; j < c; j++) {
                    printf("%p", arr[r][c]);
            }
            printf("\n");
}


    return arr;


}

I expected to be able to print out and see the contiguous memory locations of each spot in the array, but I am never reaching that point in my code, because when I run it, i get a segmentation fault. Would appreciate any help.

Upvotes: 2

Views: 51

Answers (1)

monkeymatt07
monkeymatt07

Reputation: 66

Seeing your program i see 3 errors one while you allocate memory for 2D-array,one while you're printing and another one is how you declare the function. First malloc is ok,the second one is wrong cause you already allocated memory for r(size of row) pointers so it's just like if you have * arr[r],so to allocate memory correctly now you should allocate memory just for int and not for int*. Second error while printing you put as index for row and column the values r and c,but r and c are the size of matrix , as we know the size of an array or 2D-array goes from 0 to size-1,in your case goes from 0 to r-1 and from 0 to c-1. Third error you should declare the function not as int but as int** cause you want to return a matrix so the return type is not int but int**. I change your code to make it work correctly,it should be work.

    int** allocate_space_2D_array(int **arr, int r, int c) {
          int i,j;

            arr = malloc(sizeof(int *) * r);
                  for (i = 0; i < r; i++)
                       arr[i] = malloc(sizeof(int ) * c);

            for (i = 0; i < r; i++) {
                 for (j = 0; j < c; j++) {
                       printf("%p", arr[i][j]);
                 }
              printf("\n");
            }


return arr;


}

Upvotes: 1

Related Questions