-3
  1. Why is sizeof giving the wrong output?
  2. What is meant by void pointer? Why is it 4 bytes?

In this code:

struct s1
{
    int p;
    void *q;
    char r;
};
struct s2
{
    int p;
    char r;
    void *q;
};
int main()
{
    struct s1 s;
    struct s2 r;
    printf("%d %d",sizeof(s),sizeof(r));
    printf("\n");
    printf("%d %d %d",sizeof(int),sizeof(char),sizeof(void*));
    return 0;
}

I am getting output as 12 but I think sizeof should give 9 as answer.

What is this padding I have heard about in many posts?

jww
  • 97,681
  • 90
  • 411
  • 885
Danny
  • 11
  • 3
  • 1
    Yes, padding, you've heard of it, did you try google for it? There are many useful result if you google , e.g, *c struct padding* – Yu Hao Aug 27 '14 at 03:16
  • possible duplicate of [structure padding and structure packing](http://stackoverflow.com/questions/4306186/structure-padding-and-structure-packing) – Bill Lynch Aug 27 '14 at 03:17
  • the return type of `sizeof` is `size_t` which is an unsigned type and you need `%zu` to print it. Printing with the wrong format is undefined behavior – phuclv Aug 27 '14 at 03:51
  • Next time, rather than ask why the compiler is wrong, consider alternates sources. – chux - Reinstate Monica Aug 27 '14 at 03:54
  • Suggest work on reformatting code (see my edits). – david.pfx Aug 27 '14 at 04:10

1 Answers1

2

It is not giving wrong output. The size of int on your system would be 4, the size of a void pointer also 4, and while char can usually be 8 bits long, the struct itself will not be 9 bytes long, as most systems are at least 32 bit, so the compiler is "padding" them to be multiples of 4 bytes. A void pointer is just a pointer that can point to anything.

vsz
  • 4,811
  • 7
  • 41
  • 78