"How to use long long data-type rather than pointers data-type to modify other variables ?"

"How to use long long data-type rather than pointers data-type to modify other variables ?"

本文关键字:long to data-type other variables modify rather How use than pointers      更新时间:2023-10-16

我正在学习 c++,发现 POINTER 类似于整数,所以我很好奇我是否可以从 LONGLONG实现POINTER,我知道这不是一个好主意但这样做会很有趣。在这里,我的想法是将pointer转换为数据类型(例如xpointer)之类的int,然后在可能的情况下使用xpointer访问和修改其包含的地址内容!

因此,为了做到这一点,我尝试将指针存储在LONG LONG类型中,但是它溢出了,所以出现了错误。

#include <iostream>
using namespace std;
int main()
{
int x = 1923;
long long xpointer;
xpointer = (int)&x;
cout << xpointer << endl;
return 0;
}

我知道指针太大而无法存储在LONG LONG中,所以在这里遇到了错误,您能建议我实现目标的方法吗?

这是供参考的错误消息。

error: cast from pointer to smaller type 'int' loses information
xpointer = (int)&x;
^~~~~~~
1 error generated.

PS:在这里我犯了一个错误,将x转换为int而不是long long所以它溢出了,除此之外,我如何使用xpointer来修改或检索数据,就像我们使用指针变量所做的那样如果可能的话?

问题的本质是你的代码旨在向自己的脚开枪,而你误解了脚伤是自然原因。

例如,在你正在编译的环境中,long long实际上足够大,可以存储指针†,所以没有理由不能编写这样的代码:

int x = 1923;
long long xpointer;
xpointer = reinterpret_cast<long long>(&x); //Valid on a 64-bit x86 CPU compiled with GCC
cout << xpointer << endl; 
return 0;

但是您的代码相当于xpointer = reinterpret_cast<int>(&x);,这在您的环境中无效。int的大小与long long†不同,如果要转换为后者,则需要对该类型进行快速转换。不是中间类型(int),然后隐式扩展到正确的类型(long long),这将导致警告或错误。

将来,如果您确实打算将指针存储为整数,则应选择std::intptr_t,因为 [if该类型是为您的环境定义的] 它保证足够大以将指针存储为整数。

int x = 1923;
intptr_t xpointer = reinterpret_cast<intptr_t>(&x); //Guaranteed to be valid if intptr_t is defined
cout << xpointer << endl; 
return 0;

†请注意,并非所有环境都具有与 64 位 x86 环境中的 GCC 相同的整数大小(包括intlong long)。在您的情况下,分别是 32 位和 64 位,但如果您改为针对不同的环境进行编译,这些数字(尤其是前者)可能会有所不同。


如果您随后打算实际使用存储在xpointer中的指针来修改它指向的数据,则需要将指针投射回去。如果不指示编译器将其视为指针,则无法操作xpointer指向的数据。

int x = 1923;
intptr_t xpointer = reinterpret_cast<intptr_t>(&x);
cout << xpointer << endl; 
int* ptr = reinterpret_cast<int*>(xpointer); //Legal If-and-only-If xpointer has not been changed
*ptr = 2019;
cout << x << endl; //Should print "2019"
cout << *ptr << endl; //Should print "2019"
return 0;

但请注意,如果您尝试对指针本身执行任何类型的算术运算,您将很快转向未定义行为领域,并且无法再保证程序的行为:

int x = 1923;
intptr_t xpointer = reinterpret_cast<intptr_t>(&x);
cout << xpointer << endl; 
int* ptr = reinterpret_cast<int*>(xpointer); //Legal If-and-only-If xpointer has not been changed
*ptr = 2019;
cout << x << endl; //Should print "2019"
xpointer++;//Legal, but...
int* ptr2 = reinterpret_cast<int*>(xpointer); 
*ptr2 = 2020; //This is now undefined behavior
cout << x << endl; //Legal on its own, but because of preceeding undefined behavior,
//this may not do what you expect.
return 0;

int(在现代编译器中)是32位。指针为 32 或 64 位。您的编译可能是使用 64 位编译器进行的,因此intint*之间的错误。

除此之外,C++是一种强类型语言,或者我们可以简单地用汇编语言编写它而忘记类型。

int 与指针不同,long long 与指针不同。你需要丑陋的 C 风格转换。

建议,读一本好书。

在标准C++中,intptr_t 是一个整数类型,保证足够大以容纳指针。 如果要将地址存储在整数中,请使用该地址。

相关文章: