From http://www.doc.ic.ac.uk/teaching/projects/Distinguished03/AndrewSuffield.pdf:
#include <string.h>
struct x
{
char s[10];
int a[4];
};
void bang(struct x *d)
{
strcat(d->s, "!");
}
int main(void)
{
struct x d;
strcpy(d.s, "012345678");
d.a[0] = 3;
d.a[1] = 2;
d.a[2] = 1;
d.a[3] = 0;
bang(&d);
return a[0];
}
In this example, struct x contains a 10-byte string immediately followed by a 4-integer array. d is initialized with a 9-character string (occupying 10 bytes because of the trailing NULL) and four integers. bang() appends a ! to the string, making it “012345678!” plus a trailing NULL.
The NULL byte at the end of the string will overwrite the first byte of d.a[0]. On a
big-endian host, this will have no effect because that byte was already zero. On a little-endian host, this will change the value of d.a[0] to zero
Two questions:
- Will there not be structure holes present between s & a and so the above argument does not hold. gcc gives return vaue as 3.
- return a[0] does not work on my system (gcc).
strcata longer string.return a[0]is clearly a typo. It should readreturn d.a[0].