printf和指针 [英] printf and pointers

查看:104
本文介绍了printf和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是正确的格式说明符以打印指针(地址)?

在使用 printf 打印指针时,是否将指针强制转换为 void * ?换句话说,在类似

When printing a pointer using printf, is it necessary to cast the pointer to void *? In other words, in code like

#include <stdio.h>
int main() {
    int a;
    printf("address of a = %p\n", &a);
}

参数应为(void *)& ; a gcc 在没有进行显式强制转换时似乎没有发出任何警告。

should the argument really be (void *) &a? gcc doesn't seem to give any warnings when no explicit cast is made.

推荐答案

是的,需要强制转换为 void *

Yes, the cast to void* is required.

int a;
printf("address of a = %p\n", &a);

& a 类型为 int * ; printf的%p 格式要求参数类型为 void * int * 参数被 not 隐式转换为 void * ,因为 printf 不提供第一个参数(格式字符串)以外的参数的类型信息。格式字符串之后的所有参数均已应用默认参数提升;这些促销活动不会将 int * 转换为 void *

&a is of type int*; printf's "%p" format requires an argument of type void*. The int* argument is not implicitly converted to void*, because the declaration of printf doesn't provide type information for parameters other than the first (the format string). All arguments after the format string have the default argument promotions applied to them; these promotions do not convert int* to void*.

可能的结果是 printf 看到一个实际上为 int * 类型的参数并将其解释为 if void * 类型。这是类型转换,而不是转换,并且具有未定义的行为。如果 int * void * 碰巧具有相同的表示形式,则可能会起作用,但是语言标准确实即使是暗示也不能保证。我所描述的类型处理只是一种可能的行为。

The likely result is that printf sees an argument that's really of type int* and interprets it as if it were of type void*. This is type-punning, not conversion, and it has undefined behavior. It will likely happen to work if int* and void* happen to have the same representation, but the language standard does not guarantee that, even by implication. And the type-punning I described is only one possible behavior; the standard says literally nothing about what can happen.

(如果您对具有可见原型的非变量函数执行相同的操作,那么编译器就知道了这一点。参数类型为 void * 的调用,那么它将生成代码以执行隐式 int * - to- void * 转换。这里不是这种情况。)

(If you do the same thing with a non-variadic function with a visible prototype, so the compiler knows at the point of the call that the parameter is of type void*, then it will generate code to do an implicit int*-to-void* conversion. That's not the case here.)

这篇关于printf和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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