Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to malloc 2D arrays? [duplicate]

I need to create a two dimensional array. Presently I created it as int a[100][100]

but I need to allocate the memory dynamically using malloc in C language. I used the code

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

int main(void)
{     
    int n=6, m=5, i, j;
    int **a = malloc(n * sizeof(int *));
    for(i = 0; i < m; i++)
          a[i] = malloc(m * sizeof(int));

    for( i = 1; i <= n; i++ )
    {
        for( j = 1; j <= m; j++ )
        {
            scanf("%d %d",&a[i][j]);
        }
    }

    return 0;
}

but now while inputting the elements into the array it shows SEGMENTATION ERROR.

like image 908
Hridoy Dutta Avatar asked Sep 16 '25 03:09

Hridoy Dutta


2 Answers

You say in the comments that n is the number of rows. So you need to allocate n rows each of length m. Therefore, the second for loop condition should be i < n. Also, you should check the return value of malloc for NULL in case it fails to allocate memory. I suggest the following change -

long long **a = malloc(n * sizeof(*a));
for (i = 0; i < n; i++) {
    a[i] = malloc(m * sizeof(*a[i]));
}

Please note that a multi-dimensional array is not a fundamentally new type. It's simply an array of elements where each element itself is an array (for a 2D array), an array of arrays (for a 3D) array and so on. If you are using C99, you can allocate your array cleanly and succinctly as

int nrow = 4;  // number of rows
int ncol = 8;  // number of columns

// define arr to be a pointer to an array of ncol ints, i.e.,
// arr is a pointer to an object of type (int[ncol])
int (*arr)[ncol] = malloc(sizeof(int[nrow][ncol]));

// check the result of malloc for NULL
if (arr == NULL) {
    printf("malloc failed to allocate memory\n");
    // handle it
}

// do stuff with arr
for (int i = 0; i < nrow; i++) {
    for (int j = 0; j < ncol; j++) {
        arr[i][j] = i + j;
    }
}
// after you are done with arr
free(arr);

You should also go through this - How do I work with dynamic multi-dimensional arrays in C?

like image 179
ajay Avatar answered Sep 19 '25 09:09

ajay


You have three errors: The first is that you allocate only 5 secondary arrays, but in the input you loop over 6 of them.

The second problem is that array indices are zero-based, i.e. the index start at zero and goes to the size minus one.

The third problem is that you scan for two numbers (why?), but you provide only one destination pointer to scanf.

like image 45
Some programmer dude Avatar answered Sep 19 '25 09:09

Some programmer dude