Reputation: 151
I'm a bit confused about size of element pointer points to. Including some basic code to visualize.
uint8_t var1;
uint8_t var2;
uint8_t *p[2]={&var1,&var2};
Result of sizeof(*p) is 4 instead of 1, why is that?
uint8_t var1;
uint8_t *p=&var1;
In this code result is correct sizeof(*p) is 1.
What i'm missing?
Upvotes: 2
Views: 3413
Reputation: 199
sizeOf(*p)
This computes the size of the type which is at the address stored in the value of p
... ie, pointer to uint8_t.
sizeOf(*p[0])
This is the size of the type at the address stored in the value of the zero'th element of the array which begins at the address stored in the value of p
.
uint8_t *p[2]={&var1,&var2};
This declares that the value of p
is the address of the first object in an array of pointers to uint8_t.
This does NOT dereference p
. Neither * nor [] have that meaning for lvalues.
The semantics of the dereference operator make more sense if, instead of treating it like a command, you think of it as a mathematical term you do algebra with...
"√ 2" : "the square root of 2"
" *p" : "the dereference of p"
...
"x = *p" : "set the value of x to the dereference of p"
"int *p" : "has type int: the dereference of p"
Upvotes: 0
Reputation: 67820
It is not the size of pointer but the size of the referenced object.
in the first example it is pointer, in the second uint8_t
it is easy to confirm:
uint8_t v8;
uint16_t v16;
uint32_t v32;
uint64_t v64;
double vd;
float vf;
uint8_t *v8p = &v8;
uint16_t *v16p = &v16;
uint32_t *v32p = &v32;
uint64_t *v64p = &v64;
double *vdp = &vd;
float *vfp = &vf;
volatile size_t sizes[] = {sizeof(*v8p), sizeof(*v16p), sizeof(*v32p), sizeof(*v64p), sizeof(*vdp), sizeof(*vfp)};
and the result:
(using the M4 uC - STM32F476)
Upvotes: 0
Reputation: 34585
Note that the array p
decays to a pointer, and as the array is itself an array of pointers, that's a pointer too.
#include <stdio.h>
int main(void)
{
char var1;
char var2;
char *p[2] = { &var1, &var2 };
printf("%zu\n", sizeof(*p)); // size of each element
printf("%zu\n", sizeof(**p)); // size of dereferenced element
return 0;
}
Program output
4 1
Upvotes: 2
Reputation: 11047
This is because in your first example, loosely speaking, p
is a so called double pointer or a pointer to a pointer because it is defined as a pointer to an array. So when you de-reference it, *p
you get a pointer, not the object of type uint8_t.
So the size of a pointer on ARM M4 is actually 4 bytes.
Upvotes: 0