Dudo
Dudo

Reputation: 27

Scanning to 2d array and then passing it to function - C

My program is getting segmentation fault if I allocate function as 1D array and then pass it to function. It is built for 2d array. Problem is, that I can't find out how to allocate 2d array and how to pass it correctly into function. Hope all is explained clearly. If you know what is wrong please try to lead me on correct way to fix it. Many thanks. Here is code:

int main()
{
    int i, j, size;

    scanf("%d", &size);
    int *a;

    //here i try to allocate it as 2d array
    *a = (int *)malloc(size * sizeof(int));
    for (i=0; i<size; i++)
    {
         a[i] = (int *)malloc(size * sizeof(int));
    }
    //here i scan value to 2d array
    for (i = 0; i < size; i++)
        for (j = 0; j < size; j++){
            scanf("%d", &a[i][j]); }

   //here i pass array and size of it into function
   if (is_magic(a,size))

function header looks like:

int is_magic(int **a, int n)

Upvotes: 0

Views: 86

Answers (2)

dbush
dbush

Reputation: 223937

This doesn't work:

*a = (int *)malloc(size * sizeof(int));

Because a has type int * so *a has type int, so it doesn't make sense to assign a pointer to that. You're also attempting to dereference a pointer which has not been initialized yet, invoking undefined behavior.

You need to define a as an int **:

int **a;

And assign to it directly on the first allocation, using sizeof(int *) for the element size:

a = malloc(size * sizeof(int *));

Note also that you shouldn't cast the return value of malloc.

Upvotes: 3

Achal
Achal

Reputation: 11921

Scanning 2D array ? For that you need to take a as of int** type not just int* type. For e.g

 int **a = malloc(NUM_OF_ROW * sizeof(int*)); /* allocate memory dynamically for n rows */

And then allocate memory for each row for e.g

for (i=0; i<size; i++){
    a[i] = malloc(NUM_OF_COLUMN * sizeof(int)); /* in each row how many column, allocate that much memory dynamically */ 
}

Upvotes: 1

Related Questions