【问题标题】:No error at all, why?完全没有错误,为什么?
【发布时间】:2017-08-08 17:03:26
【问题描述】:

我正在测试这段代码,但为什么完全没有错误?

#include <stdio.h>

int main()
{

    int a = 1025;
    int *p;
    p = &a;

    // now I declare a char variable , 
    char *p0;
    p0 = (char*) p; // type casting
    printf("", sizeof(char));

    // is %d correct here ?????
    printf("Address = %d, value = %d\n", p0, *p0);

}

我的问题: %d 在这里正确吗?既然%d 是整数而不是字符,为什么完全没有错误?

【问题讨论】:

  • 实际上问题出在您传递地址的第一个%d:您应该使用%pprintf("Address = %p, value = %d\n", (void *)p0, *p0); 对于第二个 char 值刚刚提升为 int
  • 此外,错误/警告还取决于您如何编译代码:使用gcc -Wall -Wextra -pedantic-errors test.c -o test -std=c11 -g,您有warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=] printf("Address = %d, value = %d\n", p0, *p0);

标签: c printf format-specifiers


【解决方案1】:

这是未定义的行为,因为 p0char*,代码 printf("Address = %d, value = %d\n", p0, *p0)%d 不是字符指针的有效转换说明符。

【讨论】:

  • constraint violation...你能详细说明一下吗?
  • 谢谢,只是投了反对票,因为你绝对错了。 :)
  • @SouravGhosh 你好先生,我已经改变了我的答案。
  • %d is not a valid conversion specifier for character pointers 事实上,它不是 any 指针。
【解决方案2】:

你的情况

 p0 = (char*) p;

是有效的,因为char * 可用于访问任何其他类型。相关,引用C11,章节§6.3.2.3

[...] 当指向对象的指针转换为指向字符类型的指针时, 结果指向对象的最低寻址字节。的连续递增 结果,直到对象的大小,产生指向对象剩余字节的指针。

但是,如果

    printf("Address = %d, value = %d\n", p0, *p0);

导致undefined behavior,因为您将指针 (p0) 传递给 %d(查看第一“对”转换说明符和相应的参数)。您应该使用%p 并将参数转换为void *,类似于

   printf("Address = %p, value = %d\n", (void *)p0, *p0);

那么,回答

完全没有错误,为什么?

因为问题不在于编译器应该抱怨的语法或任何约束违规。这纯粹是滥用给定的权力。 :)

【讨论】:

  • 注意,一些编译器会警告格式说明符不匹配。例如。最新版本的 gcc 和 clang 与 -Wall
  • @M.M.:许多非最新版本也有。它肯定出现在 2.95(c. 1999)中,我认为它已经很旧了。
猜你喜欢
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 2014-09-07
  • 2011-06-18
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
相关资源
最近更新 更多