Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to 2D arrays C, C++

I'm learning about pointers:

int x[10]; 
int *p = &x

this would make a pointer type int to the first element. So, if I had 2D array, I need to use double pointer: first pointer would point to the second dimension of the array. This means :

int x[3][4] = {{1,2,3,4},{5,6,7,8},{9,9,9,9}};

and when I want to point to it I must declare the size of the second dimension like this, right ?

int *p[4] = x;

or there is another way by typing : int **p; ?

and int *p[4] is array of integer pointers which takes 4 * (sizeof(int*)), right?

like image 201
Hasan alattar Avatar asked Jan 30 '16 12:01

Hasan alattar


3 Answers

this would make a pointer type (int) to first element ..

No.
&x is the address of array x and is of type int (*)[10] and you can't assign it to a int * type. Both are incompatible types.

So, if I had 2D array, I need to use double pointer: first pointer would point to the second dimension of the array.

No.
In expressions, arrays converted to pointer to its first elements except when an operand of sizeof and unary & operator. Therefore, in this case the type of x will be int (*)[4] after conversion. You need a pointer to an array of 4 int instead of an array of 4 pointers

 int (*p)[4] = x;
like image 86
haccks Avatar answered Nov 17 '22 20:11

haccks


To add, the first example is not correct.

x is an array of 10 ints. p is a pointer to int and not a pointer to an array of 10 ints. When assigned to p, x decays to the type pointer to int.

The assignment should be simply:

int* p = x;
like image 32
2501 Avatar answered Nov 17 '22 21:11

2501


Example program:

#include <stdio.h>
main(int argc, char* argv[])
{
    int x[3][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 987, 9, 9 } }; 
    int(*p)[4] = x; printf("p[2][1] %d", p[2][1]); 
    printf("\nsizeof(p) is : %d \nsizeof(*p) is : %d\n", sizeof(p), sizeof(*p)); 
}

Output

p[2][1] 987
sizeof(p) is : 4
sizeof(*p) is : 16

In my system (as in yours) int and pointers are 32 bits. So the size of a pointer is 4 and the size of an int is 4 too.

p is a pointer first of all. Not an array. A pointer. It's size is 4 no less no more. That's the answer to your question

Now, just to add some useful information:

p is a pointer to an array of 4 integers. The size of what p points to is 4*4==16. (Try to change int to short in the example program, you'll have sizeof(*p) is : 8)

I can assign p=x because the type is correct, now p contains the address of x and p[0] is the same as x[0] (the same array of 4 int). p[2][3] is the same as x[2][3] and *(p[2]+3). p[2] points to the element 2 of x and p[2]+3 points to the element 3 of x[2]. (all indexing is 0 based)

like image 24
edc65 Avatar answered Nov 17 '22 20:11

edc65