【问题标题】:Is it possible to manually allocate memory location to a pointer in c++?是否可以手动将内存位置分配给 C++ 中的指针?
【发布时间】:2022-07-30 15:10:21
【问题描述】:

我有一个 c++ 程序,其中有一个整数变量 a,它存储在内存位置 0x16f29782c。现在如果我想将相同的内存分配给一个int指针ptr,我可以访问相同的变量吗?

代码

    #include <iostream>
    using namespace std;
    
    int main(){
         int * ptr, i=10;
         ptr = (int *) 0x16f29782c;
         cout<<ptr<<endl;
         cout<<*ptr<<endl;
       
         return 0;
    }

输出

    User% g++ test.cpp
    User% ./a.out     
    0x16f29782c
    zsh: segmentation fault  ./a.out

为什么会这样?

【问题讨论】:

  • 因为操作系统不认为您拥有该位置的内存。你从哪里得到的地址?
  • 恕我直言,无法以您理解的方式回答该问题。考虑阅读good book

标签: c++ pointers memory


【解决方案1】:
@Suvasish das
We should not use garbage memory.
ptr = (int *) 0x16f29782c;
Hence the program was crashing.
This is some thing like obtaining the address from near by planet and using that address to set my value :)
allocate memory using
    ptr = new int;
    ptr = new int(10);
    ptr = new int[10];
based on your requirement whether to handle new int/array.

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 2021-03-22
    • 1970-01-01
    • 2021-02-14
    • 2021-04-13
    • 2014-01-06
    • 2011-01-16
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多