How about if the target hardware of the C compiler is not byte
addressable and instead only word addressable.
Ofcourse sizeof(struct sample) is not necessarily equal to the sum of
the sizes of its members, due to word alignment requirements, requiring
each char to be word aligned.
Suppose memory addressing requires all addresses to be word aligned.
So
1) sizeof(char) = 1
2) sizeof(int) = 4
3) sizeof(address word) = 4
Then suppose
struct sample
{
int *p;
char c;
char last;
}
So
sizeof(struct sample) = 12
and
offsetof(struct sample, p) = 0
offsetof(struct sample, c) = 4
offsetof(struct sample, last) = 8
Hence
sizeof(struct sample) != offsetof(struct sample, last).
--------------------------- CODE ------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
int main(){
size_t sz;
struct sample{
char c;
int i;
};
sz=sizeof(char);
printf("size of char =%d\n",sz);
sz=sizeof(int);
printf("size of int =%d\n",sz);
sz=sizeof(struct sample);
printf("size of struct sample =%d\n",sz);
sz=offsetof(struct sample,c);
printf("offset of c =%d\n",sz);
sz=offsetof(struct sample,i);
printf("offset of i =%d\n",sz);
exit(0);
}
---------------------------------------------------------------
Output on my PC :
size of char =1
size of int =4
size of struct sample =8
offset of c =0
offset of i =4
regards
balbir thomas
On Sun, 2008-07-20 at 11:59 +0000, Saifi Khan wrote:
> Hi all:
>
> Please forgive me, if this sounds like a basic question.
>
> Consider this simple C struct
>
> struct sample
> {
> int *p;
> char c;
> ...
> char last;
> }
>
> In what scenarios,
> sizeof(struct sample) != offsetof(struct sample, last)
>
> Thanks in advance.
>
> thanks
> Saifi.
>
>
>
>