xBm
xBm

Reputation: 69

What is the difference between 2d array pointers and *arr[]?

I'm trying to understand what is the difference between an array like this:

int arr[2][2] = {{0, 1}, {2, 3}};
int* pArr = (int*)arr;
for(int i = 0; i < 4; i++)
{
    printf("%d ", pArr[i]);
}

and this:

int* foo[2] = {arr1, arr2}; // Let's say the length of arr1 is 3 and arr2 is 1
int* pFoo = (int*)foo;
for(int i = 0; i < 4; i++)
{
    printf("%d ", pFoo[i]);
}

They look pretty much the same to me but the output is completely different. I'm getting strange results, if i do what i gave here as an example than it give me big integers, but if i add more arrays and items it gives me smaller integers too. output example: Output

*in the outout image: The upper integers are the first 2d array and the bottom integers are the second array pointer.

Can someone explain to me please why this behavior is happening?

Upvotes: 2

Views: 92

Answers (2)

John Bollinger
John Bollinger

Reputation: 181932

Can someone explain to me please why this behavior is happening?

With ...

int* foo[2] = {arr1, arr2}; // Let's say the length of arr1 is 3 and arr2 is 1

... foo is declared as an array whose elements are of type int *. You do not present the definitions of arr1 and arr2, but let's say they are arrays of int -- then in the initializer expressions they "decay" to pointers to their first elements, which have the correct type for elements of foo, so that's all fine.

But pointers are not integers. You declare pFoo as an int *, but you initialize it with an int ** converted to int *:

int* pFoo = (int*)foo;

Converting the pointer's type does nothing to the data to which it (actually) points, and since pFoo ends up pointing to data that aren't actually ints, accessing those data through pFoo produces undefined behavior.

Perhaps you were looking for this:

int **pFoo2 = foo;  // note: no cast needed

Now pFoo2's type, int **, is the same as the type to which foo naturally decays, and you can access the elements correctly:

printf("%d", pFoo2[0][0]);

Note that you are still accessing arr1 and arr2 through pFoo2, indirectly. You must still respect their lengths, even though those lengths are not the same as each other, and are not evident from the type of pFoo2 or of foo.

Upvotes: 1

wallyk
wallyk

Reputation: 57804

A multi-dimensional array is a single block of memory. An array of pointers to data that is not necessarily contiguous (a single block).

The latter is useful for managing sparse arrays or where each pointed to subarray isn't necessarily the same size.

Upvotes: 2

Related Questions