Im quite confused that what is difference between these two initializations:
int (*p)[10];
and
int *p[10]
I know they both can point to 2D array whose element count in row is 10....
To declare an array in C, we use the syntax: dataType arrName[arrSize]; Here, the dataType refers to the type of array, which can be an integer, float, a character, or a pointer.
Array Initialization Using a Loop An array can also be initialized using a loop. The loop iterates from 0 to (size - 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.
The first is a pointer to array, the second is an array of pointers.
To elaborate a bit on the correct answers here already:
The first line:
int (*p)[10];
declares that "p" is a pointer to the memory address of an array with the capacity of 10 ints. It can be read in English as: "integer-pointer 'p' points to 10 sequential ints in memory".
The second line:
int *p[10]
Declares that "p[]" is an array of 10 pointers to integers. This is an array of memory addresses that point to integers. In this case, "p" is a sequence of 10 pointers in memory (which happen to be the memory addresses of other ints).
int (*p)[10];
+------+ +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
| p | =========================>|(*p)[0]|(*p)[1]|(*p)[2]|(*p)[3]|(*p)[4]|(*p)[5]|(*p)[6]|(*p)[7]|(*p)[8]|(*p)[9]|
+------+ +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
sizeof p
will return sizeof (void *)
(4 on 32 bit systems, 8 on 64 bit systems)
sizeof *p
will return 10*sizeof (int)
(40 on most systems)
int *p[10]; is the same as int* (p[10]);
p
+------+------+------+------+------+------+------+------+------+------+
| p[0] | p[1] | p[2] | p[3] | p[4] | p[5] | p[6] | p[7] | p[8] | p[9] |
+------+------+------+------+------+------+------+------+------+------+
sizeof p
will return 10*sizeof (void *)
(40 on 32 bit systems, 80 on 64 bit systems)
sizeof *p
will return sizeof (int *)
(4 on 32 bit systems, 8 on 64 bit systems)
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