简体   繁体   中英

How to create a pointer to a buffer from char []

如果您有缓冲区的内存地址,并且该地址存储在char中,例如: char bufferAddress[] = "0024ABC3" ,如何使用bufferAddress创建指针,以便可以访问缓冲区中的变量?

If you can get the string into a number, then you can try something like this:

void *ptr = reinterpret_cast<void*> (0x0024ABC3);

There are a few other threads on here that deal with assigning addresses to pointers directly, so you could check those out as well. Here's one: How to initialize a pointer to a specific memory address in C++

You can do the task using std::istringstream . For example

#include <iostream>
#include <sstream>

int main() 
{
    char bufferAddress[] = "0024ABC3";
    std::istringstream is( bufferAddress );
    void *p;

    is >> p;

    std::cout << "p = " << p << std::endl;  

    return 0;
}

The output is

p = 0x24abc3

If the buffer has type char * then you can reinterpret this pointer to void to pointer to char. For example

char *buffer = reinterpret_cast<char *>( p );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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