可以在'printf'函数中使用'&'吗?

时间:2019-06-01 04:40:40

标签: c printf

提到

Here,我们可以在'printf'函数中使用,以便获取变量的地址,这就是它的代码用途:

/**
 * C program to get memory address of a variable
 */

#include <stdio.h>

int main()
{
    int num = 10;

    printf("Value of num   = %d\n", num);

    /* &num gets the address of num. */
    printf("Address of num = %d\n", &num);

    printf("Address of num in hexadecimal = %x", &num);

    return 0;
}

和输出:

  

num的值= 10

     

num的地址= 6356748

     

以十六进制表示的num地址= 60ff0c

但是当我使用gcc -o a a.c编译代码(保存为 a.c )时,收到以下警告:

  

a.c:在“ main”功能中:

     

a.c:14:12:警告:格式为'%d'的类型为'int'的参数,但是   参数2的类型为“ int *” [-Wformat =]        printf(“ num的地址=%d \ n”,&num);               ^

     

a.c:16:12:警告:格式“%x”期望参数类型为“无符号”   int”,但参数2的类型为“ int *” [-Wformat =]        printf(“ num的十六进制地址=%x”,&num);

我的问题是:

  • 可以在 printf 功能中使用吗?
  • 如果是,为什么我会收到警告?

1 个答案:

答案 0 :(得分:3)

  

可以在&函数中使用printf吗?

是的。 prefix & operator的一元“地址”可以在许多需要表达式的上下文中使用。

  

如果是,为什么我会收到错误消息?

这不是错误,而是有用的警告。您的编译器正在帮助您

在许多计算机和ABI上(包括我的Linux / Debian / x96-64),指针有8个字节,而int只有4个字节。通过使用sizeof进行检查。

您需要广播(执行type conversion)以避免警告。

printf("address of num=%d=%#x\n", (int)&num, (int)&x);

但是打印地址的正确方法是(使用(void*)只是为了提高可读性,如果需要,可以将其删除):

printf("address of num is %p\n", (void*) &num);

在使用前先阅读documentation of printf

并且养成阅读代码中使用的 any 函数文档的好习惯。使用当前的网络搜索技术,查找起来非常容易。

阅读和理解文档的能力是软件开发中最重要的技能之一。利珀特(Lippert)的Teach yourself programming in ten years博客也请阅读Norvig的How to debug small programs,这是必须考虑的内容。另请阅读What every C programmer should know about undefined behavior,这也很重要。

相关问题