gpt4 book ai didi

c - 当我尝试将变量的地址分配给声明为指向不同类型的变量的指针时,为什么会收到警告?

转载 作者:行者123 更新时间:2023-11-30 18:37:22 25 4
gpt4 key购买 nike

看一下下面的程序。我不明白的是,为什么我必须将变量 x 的地址转换为 char* ,如果你考虑一下它实际上是绝对没有用的。第二。我真正需要的只是变量的地址,声明语句 char* ptr 已经提供了所有必要的类型信息。

#include <stdio.h>


int main(void) {
int x = 0x01020309;
char* ptr = &x; /* The GCC compiler is going to complain here. It will
say the following: "warning: initialization from
incompatible pointer type [enabled by default]". I
need to use the cast operator (char*) to make the
compiler happy. But why? */

/* char* ptr = (char*) &x; */ /* this will make the compiler happy */

printf("%d\n", *ptr); /* Will print 9 on a little-endian machine */


return 0;
}

最佳答案

C Standard6.2.5 类型,第 28 段指出:

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

由于不同类型的指针可能有不同的实现或约束,因此您不能假设从一种类型转换为另一种类型是安全的。

例如:

char a;
int *p = &a

如果实现对 int 有对齐限制,但对 char 没有对齐限制,则会导致程序无法运行。

关于c - 当我尝试将变量的地址分配给声明为指向不同类型的变量的指针时,为什么会收到警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com