Search code examples
cpointersstructuresizeof

sizeof pointer to structure surprise


typedef struct {
  char a[5];
  char b[7];
}footype;

void actOnFooishThings(footype *pfoo){
  printf("Address of pfoo = %d\r\n", pfoo);
  printf("Address of pfoo + 1 = %d\r\n", pfoo + 1);
  printf("Size of pfoo = %d\r\n", sizeof(pfoo));
  return;
}

void main() {
  footype bar;
  printf("Size of bar = %d\r\n", sizeof(bar));
  actOnFooishThings(&bar);
}

output :

Size of bar = 12
Address of pfoo = 537394080
Address of pfoo + 1 = 537394092
Size of pfoo = 4

Since adding 1 to pfoo produced the result I expected (12 bytes ahead of base address) I am surprised that sizeof did not result in "12". I understand the "4". It is telling me the size of a pointer variable but it seems inconsistent with the pfoo + 1 result. How to I retrieve the size of pointer pfoo? Do I do something silly like (pfoo + 1) - pfoo?


Solution

  • All the comments are hugely instructive. Thank you. User Dxiv gave the response I was looking for. The "correct" syntax for what I was trying to do was:

    sizeof(*pfoo);
    

    or

    sizeof(footype);
    

    Credit to user Yunnosch for pointing out my question phrasing was off. I hope I am forgiven since my knowledge at the time of the post lacked what it now has after asking the question. The question should have been "how can I determine the size of the datatype pointed to by pfoo?"