For example, if I do the following,
int array[5] = {1, 2, 3, 4, 5};
printf("%d", sizeof(array));
It would return 4 times # of elements which is 5 = 20.
But my question is don't arrays require pointers?(address) If so, since pointers have the size of 8 bytes, why isn't it included in the size?
But my question is don't arrays require pointers?(address)
Nope. An array is just a sequence of objects - in this case, a sequence of 5 int
:
+–––+
array: | 1 | array[0]
+–––+
| 2 | array[1]
+–––+
| 3 | array[2]
+–––+
| 4 | array[3]
+–––+
| 5 | array[4]
+–––+
There is no space set aside for any pointer - the expression array
will be converted (“decay”) to a pointer expression such that it evaluates to the address of the first element (unless it is the operand of the sizeof
or unary &
operators).
If so, since pointers have the size of 8 bytes, why isn't it included in the size?
Don't assume pointers are a particular size - there are still 16- and 32-bit systems in use, and pointers to different types don't have to have the same size and representation. All the world is not
a VAX
x86-64.
taking example of array[5] for float and int type array it is showing the size to be 20 (while the size of float is 4 and int is 2 both seems to be having same space don't know why) so assuming a 32 bit machine having a pointer of size 4 then array is of 4*5 =20 but for char type array it is showing size to be 5 (ie this time not multiplied by 4 ) this time on the same machine the pointer size must be 1 according to the output. and for double type array it is showing size to be of 40 (5*8) ,so the pointer size must be 8
that is it is not just 4 for 32 bit or 8 for 64 but it also different for different data types
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.