gpt4 book ai didi

c - (int) 转换如何作用于 char 数组和 char *?

转载 作者:太空宇宙 更新时间:2023-11-04 00:28:29 25 4
gpt4 key购买 nike

好吧,我相信我搜索得够多了,我找不到任何解释。

当您将 char 转换为 int 时,这是显而易见的。

char foo = 'a';
int bar = (int)foo;
printf("%i",bar); //Outputs 97 as expected.

但是当您尝试将 cast char *char 数组转换为 int 时,编译器只是给你一个警告:

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

对于 char * 你得到一个常量 int 值 - 我相信这与指针或内存有关 - 然后对于 char 数组你总是得到一些变量 int 值。

char* foo = "baz";
int bar = (int)foo;
printf("%i",bar);

char qux[]="something";
int bar2 = (int)qux;
printf("%i",bar2);

这听起来像是一个不必要的问题,但我想知道原因。

最佳答案

尝试将指针转换为某些整数 类型可能会导致未定义的行为 (UB)。

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined.* ... C11dr §6.3.2.3 6

(int)foo 可以生成警告,例如“警告:从指针转换为不同大小的整数”,因为存在 UB 潜力。 @4386427

char* foo = "baz";
int bar = (int)foo; // potential UB.

为避免这种 UB,在将对象指针 转换为整数(不是函数指针)时,使用可选类型 uintptr_tintptr_t.

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

uintptr_t
7.20.1.4 1

例子

#include <inttypes.h>

some_object* foo = ...;
uintptr_t bar = (uintptr_t)(void*)foo; // no UB

printf("0x%" PRIXPTR "\n", bar);

for a char array you always get some variable int value.

那是因为数组的转换,先转换为第一个元素的指针,再转换为整数。 int bar2 = (int)qux; 试图获取数组所在位置的值,而不是其元素值。

关于c - (int) 转换如何作用于 char 数组和 char *?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48551525/

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