简体   繁体   中英

Storing the address of a pointer into memory

For example, I have:

char* a = (char*) malloc(sizeof(char));
char* b = (char*) malloc(sizeof(char*));

How do I get the address of a into memory starting at address b ?

Couldn't you just do a *b = a ? Or am I misunderstanding the question?

取决于你所需要的(它不是完全清楚),你可以做b = a*b = &a (字面上你问,地址a到存储器中,起始地址b ),或*b = a

If you want b to point to a pointer to char (as could be deduced by looking at your malloc statement, where you allocate space for one pointer to char ), then b should actually be of type pointer to pointer to char , like this:

char*  a = (char*) malloc(sizeof(char));
char** b = (char**)malloc(sizeof(char*));

As far as I understood, what you want to achieve is to assign the address a is pointing to to the place b is pointing to? That would look like this then:

*b = a;

If you instead just want b to be a pointer to char (as you actually declared b ), and want it to point to the same address as a , then do this:

char* a = (char*)malloc(sizeof(char));
char* b = a;

That makes b point to the same location as a ; but then you also don't need to allocate space for b, because they simply point to the same address on the heap. You'll have to take care however, that you also only free the space pointed to by a and b once!

I'd also suggest reading up on the idea of pointers (eg here or here ).

Let me preface this by saying that, since b is actually going to point to a char* , you should really declare and initialize it this way:

char** b = (char**) malloc(sizeof(char*));

using char** instead of char* . But if you already know that, and still want b to have type char* for some reason, then you'd just write this:

*((char**) b) = a;

which treats b as though it were a char** , so you can store a char* in it.

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