繁体   English   中英

为什么不能将 memory 地址号分配给指针?

[英]Why can I not assign a memory address number to a pointer?

我们知道指针有名字和值,本质是变量,值是十六进制数,即memory地址。

int a = 10;
int * p = &a;

cout << p << endl;  // 0x7ffee04fe2b8

int * q = 0x7ffee04fe2b8;  // why can not assign address number to the pointer `q`?

图片


如果我分配0x0 ,它的工作原理:

int * q = 0x0;

0x0指的是NULL,是否因为解释器采取特殊处理。

我使用 CLion 编辑器。


编辑

我试图声明 as long ,也有问题:

图片


编辑

我使用 64 位 macOS。

指针值存储了一个memory地址,所以想尝试直接分配地址。 为什么我不能使用这种方法?

int a = 10;
int * p = &a;

cout << p << endl;  // 0x7ffee04fe2b8

long q = 0x7ffee04fe2b8;
cout << * (int *)q << endl;  // prints nothing

编辑

我试过这篇文章:指向特定固定地址的指针

int a = 10;
int * p = &a;

cout << p << endl;  // 0x7ffee04fe2b8

volatile unsigned int *myPointer = (volatile unsigned int *)0x7ffee04fe2b8;

cout << *myPointer << endl;  // print nothing

但为什么它不打印任何东西?

它构建成功,但是当我运行它时,它不会用*myPointer打印任何内容。

====================[ Build | untitled | Debug ]================================
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build /Users/luowensheng/CLionProjects/untitled/cmake-build-debug --target untitled -- -j 4
[100%] Built target untitled

Build finished

C语言中,您可以从常量分配地址。 这不是一个好主意。 但你可以做到。

示例编译器错误:

$ cat c-ptr-test.c
int main() {
  long *p = 0x0011223344556677;
  return 0;
}
$ make c-ptr-test
cc -Wall -W -pedantic -g -O3 -flto -fno-fat-lto-objects -pthread -MMD  -std=c11   -pthread -flto -fno-fat-lto-objects  c-ptr-test.c   -o c-ptr-test
c-ptr-test.c: In function ‘main’:
c-ptr-test.c:2:13: warning: initialization of ‘long int *’ from ‘long int’ makes pointer from integer without a cast [-Wint-conversion]
    2 |   long *p = 0x0011223344556677;
      |             ^~~~~~~~~~~~~~~~~~
c-ptr-test.c:2:9: warning: unused variable ‘p’ [-Wunused-variable]
    2 |   long *p = 0x0011223344556677;
      |         ^

两个警告,但 GCC 编译成功。

但是,在 C++ 语言中,它需要显式转换。 你应该使用reinterpret_cast但旧的 C 风格的演员也可以工作。

似乎您正在尝试分配指针,而没有告诉编译器您“想要”分配它。

您的编译器错误应如下所示

从“long int”到“int*”的无效转换

要分配地址,语法应该是int *q = (int*)0x7ffee04fe2b8; ,while (int*)表示“这个值是指针int*的地址。

或者更现代的方式: int * q = reinterpret_cast<int*>( 0x7ffebfc7019c );

但是,您必须知道自己在做什么。 除非您使用硬件寄存器编写低级代码,否则永远不要硬编码地址。

此外,每次执行代码时,其地址可能与上次不同。

尝试以下代码:或在 GCC 10.1 https://godbolt.org/z/8zn7j5

int main()
{
   int a = 10;
    int * p = &a;

    cout << p << endl;

    long addr = (long)p;
    int * q = reinterpret_cast<int*>( addr );
    cout << *q << endl;
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM