使用printf("%s",..)打印一个struct,struct的第一个变量类型是'char *',为什么可以得到一个正确的字符串存储在'char *'中? [英] use printf("%s",..) to print a struct, the struct's first variable type is 'char *', why can get a right string stored in 'char *'?

查看:49
本文介绍了使用printf("%s",..)打印一个struct,struct的第一个变量类型是'char *',为什么可以得到一个正确的字符串存储在'char *'中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,定义一个结构体如下:

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;
}

输出是:abc",我想知道为什么可以得到这个?
我猜编译器认为 printf("%s", a)printf("%s", *&a) 因为 &a 等于 &as,所以 *&a 等于 *&as,对吗?

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?

但如果是这样,如果我像这样将 int len 放在结构体的第一个:

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);
}

这次的输出是:10,为什么?
也许编译器读取 %d 所以它知道应该打印一个整数值,只打印 4 个字节?我想得到一些解释.

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.

推荐答案

你正在做的是未定义的行为...

What you're doing is undefined behaviour...

至于它为什么起作用,这取决于现在在 C 中工作的可变长度参数的性质.像 printf 这样的函数依靠格式字符串来告诉他们传递的是什么类型的参数.在您的第一个示例中,您已经表明您正在传递一个字符串 (%s),但实际上您已经传递了一个结构体.printf 函数将在堆栈中查找 char* 指针,因为您的结构以字符串开头,所以它会找到一个!如果你交换 slen 的顺序,然后用 %s 调用 printf 你要么获取垃圾输出或访问冲突.

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.

同样的规则适用于您交换了顺序的第二个示例,但这次您尝试输出一个整数.您已将整个结构传递给 printf 调用,然后该调用会在堆栈上查找 int.因为结构以 int 开头,所以你很幸运!如果您没有交换周围的字段顺序,您就会看到 10 以外的数字.

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.

这篇关于使用printf("%s",..)打印一个struct,struct的第一个变量类型是'char *',为什么可以得到一个正确的字符串存储在'char *'中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆