gpt4 book ai didi

C++ 将 char 数组存储在 int 指针中

转载 作者:行者123 更新时间:2023-12-02 12:39:02 24 4
gpt4 key购买 nike

此行中是否进行了任何类型的转换(隐式、显式):

int *p= "hello there"; 

此外,从 C/C++ 的角度来看,这种说法的正确性是什么?

注意:它在 AVR-GCC 上编译,在其他编译器上编译失败。

最佳答案

"Is there any type of casting (implicit, explicit) done in this line:"

int *p= "hello there"; 

不,尚未完成任何选角。

但是在 C++ 中你可以使用 reinterpret_cast<int*>以及const_cast<char*>如下:

int *p= reinterpret_cast<int*>(const_cast<char*>("hello there")); 

<子> See a working demo.

"Moreover what do you think about the correctness of such statement from (C,C++) point of view."

好吧,这完全取决于此类声明的用户。当然不建议这样做(因为您遇到了未指定的1行为),并且如果您不能 100% 确定自己在做什么,那就很危险。

但至少两种语言都支持这样做。

C 的更短的变体是:

int *p= (int*)"hello there";
<小时/>

"Note: it compiles on AVR-GCC and fails with other compilers."

嗯,我不知道您用于 AVR 交叉工具链的版本,但是任何半最新版本的 GCC 都应该针对此语句给出错误,例如

prog.cpp:3: error: cannot convert 'const char*' to 'int*' in initialization

<子> See demo please

我使用相当旧的 GCC 版本来构建该演示:g++ 4.3.2。如果我被正确告知的话,最新的是 5.x,并且我很确定这是可能的 to build a cross toolchain对于 AVR 来说。

<小时/>

1 这与未定义的行为略有不同。仅取决于您的硬件与这些指针地址以及对齐设置的配合。

关于C++ 将 char 数组存储在 int 指针中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30744742/

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