Stackd
Stackd

Reputation: 693

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?

Upvotes: 1

Views: 185

Answers (4)

codeling
codeling

Reputation: 11369

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 (e.g. here or here).

Upvotes: 1

ruakh
ruakh

Reputation: 183290

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.

Upvotes: 1

Igor
Igor

Reputation: 27250

Depends on what you need (it's not fully clear), you can do b = a, *b = &a (literally as you asked, the address of a into memory starting at address b), or *b = a.

Upvotes: 1

SuperTron
SuperTron

Reputation: 4233

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

Upvotes: 1

Related Questions