MrTambourineMan
MrTambourineMan

Reputation: 1045

Why this code doesn't work?

i get a segmentation here. However if i declare array as int** and use malloc, it works fine.

#include <stdio.h>

void display(int **p,int numRows,int numCols) //Second Method//
{
    printf("\n");
    int i,j;
    for (i = 0; i< numRows;i++)
    {

        for (j = 0;j< numCols;j++)
        {
            printf("%d\t",p[i][j]);
        }
        printf("\n");
    }
}

int main() {

    int arr[2][2]={{1,2},{4,5}};
        display(arr,2,2);
}

PS I don't need an alternative way, just tell me why this code doesn't work.

Upvotes: 0

Views: 627

Answers (3)

zneak
zneak

Reputation: 138041

An int** is a pointer to a pointer, while an int [2][2] contiguously stores two arrays. That's your mistake.

With int x[2][2], when you do x[1], you tell the compiler to access memory by skipping one set of two elements, and the resulting expression is an array of two elements. With int** x, when you do x[1], you tell the compiler to access memory by skipping one pointer. While you access data the same way for both, the two are simply not laid out the same way.

In memory, x[2][2] = {{1, 2}, {4, 5}} looks like this:

// 4 contiguous elements
01 00 00 00  02 00 00 00    04 00 00 00  05 00 00 00

While int** x looks like this:

// pointers to integers
aa bb cc dd  aa ab ac ad
// At [aa bb cc dd]:
    01 00 00 00  02 00 00 00
// At [aa ab ac ad]:
    04 00 00 00  05 00 00 00

Therefore, to adapt for an int**, you must create an array of int* pointers dynamically and set each entry to the lower dimension of your array.

Upvotes: 3

P0W
P0W

Reputation: 47784

Please don't neglect warnings

expected int **' but argument is of type 'int (*)[2]

arr is an array of 2 arrays of 2 integers

Use :

void display(int p[][2],int numRows,int numCols)

Upvotes: 4

caf
caf

Reputation: 239011

arr is an array of 2 arrays of 2 ints. When it's used in an expression without being the subject of either the unary & or sizeof operators, it evaluates to a pointer to its first element.

This is a "pointer to an array of 2 int", which is the type int (*)[2]. It is not a pointer to a pointer to int, which is the type int **. Furthermore, these types are not compatible, and you can't pass the former to a function expecting the latter.

An int ** must be pointing at something that itself is a pointer. The pointer you are passing to display is pointing at an array, not a pointer.

Upvotes: 6

Related Questions