缺少“%p”与 char* 等组合的 GCC Wformat 警告

问题描述 投票:0回答:1

如果我使用 GCC 13.2.0 使用

-std=c17 -Wall -Wextra -Wpedantic
编译以下代码,尽管没有在与
void*
格式说明符对应的参数中使用
"%p"
,但我不会收到任何警告。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main()
{
    const char cstr[] = "ABC";
    size_t size = sizeof cstr;
    const uint8_t ustr[] = "ABC";
    const int8_t sstr[] = "ABC";
    const char* pcstr = cstr;
    const uint8_t* pustr = ustr;
    const int8_t* psstr = sstr;
    printf("cstr ptr:  %p\n", cstr);
    printf("size ptr:  %p\n", (void*)&size); // we need cast to prevent Wformat
    printf("&cstr ptr: %p\n", (void*)&cstr); // we also need this cast
    printf("pcstr:     %p\n", pcstr);
    printf("ustr ptr:  %p\n", ustr);
    printf("pustr:     %p\n", pustr);
    printf("sstr ptr:  %p\n", sstr);
    printf("psstr:     %p\n", psstr);
    return 0;
}

阅读完问答后*什么是警告以及如何解决警告:格式'%p'期望参数类型为'void *',但是参数2在打印时具有类型'int'[-Wformat=],我应该在这里期待未定义的行为吗?我尝试了几次搜索,但您会明白对于这样一个特定的组合来说,这些搜索有多困难。

是否可能是

void*

char-ish*
 共享某些属性 
I 缺失,或者这是 GCC 中 缺失警告 的情况?希望这里有人能够阐明这个问题。

c compiler-warnings gcc-warning
1个回答
2
投票
在没有强制转换的情况下,您不会收到警告,因为

void *

 需要与指向字符类型的指针具有相同的表示形式,即 
char
signed char
unsigned char
,或任何type 是其中之一的 typedef。

这是由

C 标准第 6.2.5p28 节规定的

指向 void 的指针应具有相同的表示和对齐方式 要求作为指向字符类型的指针。

48)

    相同的表示和对齐要求旨在 暗示作为函数参数的可互换性,返回值 职能和工会成员。
所以上面的代码定义良好。

© www.soinside.com 2019 - 2024. All rights reserved.