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

徘徊边缘 提交于 2020-01-01 12:13:14

问题


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.


回答1:


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.




回答2:


You're invoking undefined behavior. Enable warnings and errors in your compiler (e.g. gcc -Wall -Wextra -Werror) and your ability to do these shenanigans will disappear.

If you really want to know, it's probably because when you pass a by value to printf(), its first member is the char* and that's what printf() sees when it looks for the string to print. In other words, you got lucky.




回答3:


You must specify which value you want to print, printf and C in general cannot guess :)

typedef struct str
{
    int len;
    char *s;
}str;
int main()
{
    str a;
    a.len = 10; // As you did there, you specify which value from your struct !
    printf("%d", a.len);
}

Otherwise it's undefined behaviour and Segfault is coming !



来源:https://stackoverflow.com/questions/26525394/use-printfs-to-print-a-struct-the-structs-first-variable-type-is-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!