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?
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;
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;
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With