【问题标题】:Get value from memory address [closed]从内存地址获取值[关闭]
【发布时间】:2019-03-20 07:36:57
【问题描述】:

我有一个存储内存地址的int* 变量,例如地址0x28c1150

我想知道,地址中存储了什么值。

编辑:

struct list {
    int value;
    list *next;
    list *head = NULL;
    void push(int n);
    void select();
    void pop();
    void top();

};

void list::push(int value) {
    list *temp = new list;

    temp->value = value;
    temp->next = head;
    head = temp;
}
void list::top(){
    list * temp = new list;

    cout << head;
}

我想打印我的列表顶部

【问题讨论】:

  • 或指向的值:std::cout &lt;&lt; *variable &lt;&lt; "\n";
  • 如果没有type,就不能有值。您期望什么类型的价值?
  • 我期待 int
  • int* 与您的代码有什么关系。我在您的代码中没有看到任何 int*
  • 您的top() 函数泄漏内存。您分配了一个新列表,然后就忘了它。

标签: c++ pointers


【解决方案1】:

如果你的变量是list*:

list* variable = new list;
variable->top();

...但是请注意,您当前的top() 函数会泄漏内存,因为您每次调用它时都会分配一个新列表,而您只是忘记了它。试试这个:

int list::top(){  
    return head->value;
}

std::cout << variable->top() << "\n";

【讨论】:

  • 非常感谢,工作正常,但你能告诉我如何在我的代码中使用这个值(如果比较的话)
  • int other_value = 10; if(variable-&gt;top() == other_value) ... ?我认为您应该编辑您的原始问题,以明确您的实际要求。现在它被搁置了。
【解决方案2】:

你必须取消引用指针:

template<class T>
void print_value_at(T* pointer) {
    T& value = *pointer; //get value in pointer
    // print value 
    std::cout << value <<std::endl;
}

如果指针为 void,则必须将其转换为原来的任何类型:

int x = 10;
// get void pointer to x
void* x_pointer_as_void = (void*)&x; 
// convert it back to a pointer to an int:
int* x_pointer = (int*)x_pointer_as_void;

【讨论】:

    【解决方案3】:

    这里是(基于当前版本的问题)

    cout << head->value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-05
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      相关资源
      最近更新 更多