use printf("%s",..) to print a struct, the struct's first variable type is 'char *', why can get a right string stored in 'char *'?

c, struct

Solution

What you're doing is undefined behaviour...

As for why it works, it's down to the nature of now variable length arguments work in C. Functions like `printf` rely on the format string to tell them what type of argument has been passed. In your first example you've indicated that you're passing a string (`%s`) but you've actually passed a struct. The `printf` function will look for a `char*` pointer on the stack, and because your struct starts with a string it will find one! If you swap the order of `s` and `len` around and then call `printf` with a `%s` you'll either get garbage output or an access violation.

The same rule applies to your second example where you have swapped the order but this time you're trying to output an integer. You've passed the entire structure to the `printf` call which then looks for a `int` on the stack. Because the struct starts with an `int` you got lucky! If you'd not swapped the field order around you'd have seen a number other than 10.

Problem

In C language,define a struct like this: ``` typedef struct str { char *s; int len; }str; int main() { str a; a.s = "abc" printf("%s", a); return 0; } ``` the output is: "abc", I want to konw why can get this? I guess the complier think `printf("%s", a)` as `printf("%s", *&a)` because &a is equal to &a.s, so *&a is equal to *&a.s, right? but if so, if I put the `int len` at the first in the struct body like this: ``` typedef struct str { int len; char *s; }str; int main() { str a; a.len = 10; printf("%d", a); } ``` this time the output is: 10, why? Maybe compiler read %d so it knows that should print a integer value, only print 4 bytes? I want to get some explain about it.

Original source