【问题标题】:(c++) Casting int to char pointer (int being character in int form)(c++) 将 int 转换为 char 指针(int 是 int 形式的字符)
【发布时间】:2016-04-13 13:01:33
【问题描述】:

所以基本上我希望能够按照这些思路做一些事情

char *test1 = "hey";
int test2 = (int)test1;
char *test3 = (char*) &test2;
printf("%s", test3);
// have the output as hey

这甚至可能吗?我知道这不能正常工作,但我只想知道是否有工作方法。是的,我想使用 char 指针和整数,所以不,我不想使用字符串

【问题讨论】:

  • 请注意,char *test1 = "hey"; 不应编译。一些编译器具有允许这样做的扩展,但您应该使用 char test1[] = "hey";const char* test1 = "hey"; 或更好的是 std::string test = "hey";
  • 什么甚至可能吗?您已经编写了一些代码,这些代码执行了一些不确定的强制转换,这些强制转换可能会或可能不会做一些明智的事情。你想完成什么?
  • 出于兴趣,为什么要这样做?
  • @JohnnyMopp - 虽然这很重要,但这并不是这里真正发生的事情。还有另一层间接,用(char*)&test2 初始化test3。注意&——它使用test2地址

标签: c++ pointers


【解决方案1】:
char *test1 = "hey";
int test2 = (int)test1;
char *test3 = (char*) test2; // Note that the ampersand has been removed
printf("%s", test3);

如果ints 和指针大小相同(通常是这样,但不能保证),可能会起作用。

但是当您分配test3 时,您使用的是test2 的地址,而不是它的值,我认为这是您真正想要做的。

【讨论】:

  • 指针通常是无符号整数。
  • 如果您想为用户提供应有的声誉,请勾选“已接受”的答案;)
  • @AhmetIpkin 此答案表现出未定义的行为,不应被接受。将指针转换为 int 是未定义的行为。将字符串文字转换为指向可变字符的指针是未定义的行为。将字符串文字(间接)转换为指向可变 char 的指针也是未定义的行为。
  • @RichardHodges 将char * 转换为int 不是未定义的行为(std::intptr_t 是可选的,大多数情况下是uint_t),您只是在读取文字(修改该地址为 UB)。铸件是 C / C++ 上定义良好的操作。将字符串文字转换为 char 指针也不是 UB,它在任何理智的编译器中都是一个错误 - 可以通过分配给 const char* 来修复。
  • @AhmetIpkin 这个问题被标记为 c++。
【解决方案2】:

代码代表未定义的行为,因此不正确。

不过,有一种方法可以合法地做你想做的事。解释见内联 cmets:

#include <cstddef>
#include <cstdint>
#include <cstdio>

int main()
{
    // string literals are const
    const char *test1 = "hey";

    // intptr_t is the only int guaranteed to be able to hold a pointer
    std::intptr_t test2 = std::intptr_t(test1);

    // it must be cast back to exactly what it was
    const char *test3 = reinterpret_cast<const char*>(test2);

    // only then will the programs behaviour be well defined
    printf("%s", test3);
}

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 2013-01-10
    • 2015-01-20
    相关资源
    最近更新 更多