Reputation: 109
I know that a pointer has a size similar to the device address architecture. But I am unable to get why same function and arguments are giving different results. Please look at the code and let me know what's the cause.
#include <stdio.h>
#include <stdint.h>
int main()
{
uint8_t a[22]={1,2,3,4,5};
uint8_t* p[2]={a};
printf("%d\n%d\n",&a,p[0]);
printf("%d,%d",sizeof(a),sizeof(p));
return 0;
}
606584768 606584768 22,16
Upvotes: 0
Views: 78
Reputation:
sizeof(a) give array size which is 22 but sizeof(b) give the size of array of pointer which consists of two pointers (2*8=16)
Upvotes: 0
Reputation: 412
Because there is a different between a and b firstly let examine a
uint8_t a[22]={1,2,3,4,5};
this line of code means a is array consists of 22 elements each element has 8 bits (one byte) so sizeof(a) is 22*1=22 secondly with respect to b
uint8_t* p[2]={a};
this line of code means b is array of pointers consists of 2 elements type of pointers which have the same size with respect to design architecture so so sizeof(p) is (2 pointer * 8 )=16
Upvotes: 1
Reputation: 123568
An expression of type "N-element array of T
" will "decay" to an expression of type "pointer to T
" except when the expression is the operand of the sizeof
or unary &
operators.
The expression a
has type "22-element array of uint8_t
", so sizeof a
will give you the same result as sizeof (uint8_t) * 22
. The expression p
has type "2-element array of pointer to uint8_t
(uint8_t *
)", so sizeof p
is the same as sizeof (uint8_t *) * 2
.
To summarize:
a == some_address;
sizeof a == 22 ( sizeof (uint8_t) should be 1)
p == some address;
p[0] == address of the first element of a
sizeof p == 2 * sizeof (uint8_t *) (assuming pointer size is 8, this will be 16)
sizeof p[0] == sizeof (uint8_t *)
Upvotes: 1
Reputation: 15172
An array and pointer are not of the same type, an array will decay to a pointer but is not itself a pointer.
sizeof(a) gives the actual size of an uint_8[22], while sizeof(p) gives the actual size of an uint8_t *[2];
Upvotes: 3