I declared the following struct in my C++ program:
struct person {
char name[10]; /* first name */
char id[10]; /* ID number */
off_t pos; /* position in file, for demonstration */
} people[] = {
{ "arnold", "123456789", 0 },
{ "miriam", "987654321", 10240 },
{ "joe", "192837465", 81920 },
};
j = sizeof(people) / sizeof(people[0]); /* count of elements */
gives j = 3 here, i.e, no of elements in the array; always even if you add or reduce the elements…
But
char b[8];
i = sizeof(b)/sizeof(b[0]);
gives the value of i = a constant = 4 on my machine.
Now thats justified as the sizeof(char*) is constant on my machine and the sizeof(char) too is constant..
But as soon as I declare the struct person, the sizeof(person*) and sizeof(person) should also be constant, and it should also yield a constant value, isn’t it???
Your compiler is wrong.
should yield
i==8.The result you’re getting for the
structsize is correct. I would switch compilers if I were you.If you were to pass
bto a function calculating the size, than you’d be right. But as the code is now, no.Also, if it was a function calculating
sizeof(people) / sizeof(people[0])which receivedpeopleas a parameter, you’d also get a constant.This is because arrays decay to pointers when passed as arguments.