c++ - const char* 到 int 转换?

标签 c++ casting char int

我想以下代码片段的行为应该是未定义的,但我只是想确保我理解正确。 假设我们有这段代码:

#include <iostream>

int main()
{
  std::cout << "mamut" - 8 << std::endl;
  return 0;
}

所以我认为它的作用是 (char*)((int)(const char*) - (int)),虽然这之后的输出很奇怪,但我并不认为它有任何实际意义。所以我的问题是关于 char* 和 int 之间的转换 - 它是未定义的,还是背后有一些逻辑?

编辑: 让我补充一下:

#include <iostream>

int main ()
{
    const char* a = "mamut";
    int b = int(a);
    std::cout << b << std::endl;
    std::cout << &a <<std::endl;
    // seems b!= &a
    for( int i = 0; i<100;i++)
    {
        std::cout<<(const char*)((int)a - i)<<std::endl;
    }

    return 0;
 }

在我变得足够大之后的输出给了我一个类似 _Jv_RegisterClasses 等的东西。 仅作记录:

std::cout << a - i << std::endl;

产生与以下相同的结果:

std::cout<<(const char*)((int)a - i)<<std::endl;

最佳答案

没有转换,您只是告诉 cout 您想要在字符串文字“mamut”减去 8 个字节的地址处打印字符串。你正在做指针运算。然后 cout 将打印该地址处的任何内容,或者可能会崩溃并烧毁,因为越界访问数组会导致未定义的行为。

编辑

关于 op 的编辑:将地址转换为 int 不一定会产生与地址相同的正确数字。地址不一定适合 int 并且最重要的是,int 是有符号类型,将地址存储在有符号类型中没有任何意义。

为了保证从指针到整数的转换没有损失,您需要使用 stdint.h 中的 uintptr_t

引用 C 标准 6.3.2.3(我相信 C++ 在这种情况下是相同的):

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. The result need not be in the range of values of any integer type.

关于c++ - const char* 到 int 转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26465725/

相关文章:

c++ - 使用 QSharedMemory 附加现有的共享内存

c# - 如果参数是 T,转换为 T 会失败吗?

objective-c - 在 C 中使用 char,指针问题, Objective-C

c++ - 静态和自动变量的 gcc 运行时声明

c++ - 使用 SWIG 为 tcl 转换的代码的段错误

java - 将 int 缩小为更小的类型

c# - 为什么根据 ReSharper 将 double-to-int 转换分配给冗余的动态变量?

谁能解释一下这段C代码吗?

sql-server - SQL Server : Replace characters different than a char in a string using no temporary table

c++ - 多重继承 - virtual 修饰符