Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory location of pointer variable itself?

Tags:

c++

pointers

Is it possible to find the memory location of a pointer variable itself?

i.e. I don't want to know the memory location the pointer is referencing, I want to know what the memory location of the pointer variable is.

int A = 5;
int *k = &A;
cout << k;

will give me the location of A. Does k have a location?

like image 348
Bill Avatar asked Mar 30 '26 03:03

Bill


2 Answers

The location of int *k is &k, like so:

// For this example, assume the variables start at 0x00 and are 32 bits each.
int    A   = 9;  // 0x00 = 0x09
int *  k   = &A; // 0x04 = 0x00
int ** k_2 = &k; // 0x08 = 0x04

// Thus:
cout << "Value of A:   " << A;   // "Value of A:   9"
cout << "Address of A: " << k;   // "Address of A: 0x00"
cout << "Address of k: " << k_2; // "Address of k: 0x04"

assert( A == *k);
assert(&A ==  k);

assert(&A ==  *k_2);
assert( A == **k_2);

assert( k == *k_2);
assert(&k ==  k_2);

A pointer is a variable, 32-bit on 32-bit binaries and 64 in 64, storing a memory address. Like any other variable, it has an address of its own, and the syntax is identical. For most intents and purposes, pointers act like unsigned ints of the same size.

Now, when you take &k, you now have an int **, with all the interesting complexities that go with that.

From int ** k_2 = &k, *k_2 is k and **k_2 is *k, so everything works about how you'd expect.

This can be a useful way to handle creating objects cross-library (pointers are rather fundamental and mostly safe to pass). Double pointers are commonly used in interfaces where you want to pass a pointer that will be filled with an object, but not expose how the object is being created (DirectX, for example).

like image 130
ssube Avatar answered Apr 01 '26 09:04

ssube


Yes. You can use &k to print out the memory location of *k.

like image 25
TheOneTeam Avatar answered Apr 01 '26 08:04

TheOneTeam