How to get address of a pointer in c/c++?
Eg: I have below code.
int a =10;
int *p = &a;
So how do I get address of pointer p?
Now I want to print address of p, what should I do?
print("%s",???) what I pass to ???.
To get the address of p do:
int **pp = &p;
and you can go on:
int ***ppp = &pp;
int ****pppp = &ppp;
...
or, only in C++11, you can do:
auto pp = std::addressof(p);
To print the address in C, most compilers support %p, so you can simply do:
printf("addr: %p", pp);
otherwise you need to cast it (assuming a 32 bit platform)
printf("addr: 0x%u", (unsigned)pp);
In C++ you can do:
cout << "addr: " << pp;
int a = 10;
To get the address of a, you do: &a (address of a) which returns an int* (pointer to int)
int *p = &a;
Then you store the address of a in p which is of type int*.
Finally, if you do &p you get the address of p which is of type int**, i.e. pointer to pointer to int:
int** p_ptr = &p;
just seen your edit:
to print out the pointer's address, you either need to convert it:
printf("address of pointer is: 0x%0X\n", (unsigned)&p);
printf("address of pointer to pointer is: 0x%0X\n", (unsigned)&p_ptr);
or if your printf supports it, use the %p:
printf("address of pointer is: %p\n", p);
printf("address of pointer to pointer is: %p\n", p_ptr);
&a gives address of a - &p gives address of p.
int * * p_to_p = &p;
Having this C source:
int a = 10;
int * ptr = &a;
Use this
printf("The address of ptr is %p\n", (void *) &ptr);
to print the address of ptr.
Please note that the conversion specifier p is the only conversion specifier to print a pointer's value and it is defined to be used with void* typed pointers only.
From man printf:
p
The void * pointer argument is printed in hexadecimal (as if
by %#x or %#lx).
You can use the %p formatter. It's always best practice cast your pointer void* before printing.
The C standard says:
The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
Here's how you do it:
printf("%p", (void*)p);
You can use %p in C
In C:
printf("%p",p)
In C++:
cout<<"Address of pointer p is: "<<p
you can use this
in C
int a =10;
int *p = &a;
int **pp = &p;
printf("%u",&p);
in C++
cout<<p;
In C++ you can do:
// Declaration and assign variable a
int a = 7;
// Declaration pointer b
int* b;
// Assign address of variable a to pointer b
b = &a;
// Declaration pointer c
int** c;
// Assign address of pointer b to pointer c
c = &b;
std::cout << "a: " << a << "\n"; // Print value of variable a
std::cout << "&a: " << &a << "\n"; // Print address of variable a
std::cout << "" << "" << "\n";
std::cout << "b: " << b << "\n"; // Print address of variable a
std::cout << "*b: " << *b << "\n"; // Print value of variable a
std::cout << "&b: " << &b << "\n"; // Print address of pointer b
std::cout << "" << "" << "\n";
std::cout << "c: " << c << "\n"; // Print address of pointer b
std::cout << "**c: " << **c << "\n"; // Print value of variable a
std::cout << "*c: " << *c << "\n"; // Print address of variable a
std::cout << "&c: " << &c << "\n"; // Print address of pointer c
First, you should understand the pointer is not complex. A pointer is showing the address of the variable.
Example:
int a = 10;
int *p = &a; // This means giving a pointer of variable "a" to int pointer variable "p"
And, you should understand "Pointer is an address" and "address is numerical value". So, you can get the address of variable as Integer.
int a = 10;
unsigned long address = (unsigned long)&a;
// comparison
printf("%p\n", &a);
printf("%ld\n", address);
output is below
0x7fff1216619c
7fff1216619c
Note:
If you use a 64-bit computer, you can't get pointer by the way below.
int a = 10;
unsigned int address = (unsigned int)&a;
Because pointer is 8 bytes (64 bit) on a 64-bit machine, but int is 4 bytes. So, you can't give an 8-byte memory address to 4 bytes variable.
You have to use long long or long to get an address of the variable.
long long is always 8 bytes.
long is 4 bytes when code was compiled for a 32-bit machine.
long is 8 bytes when code was compiled for a 64-bit machine.
Therefore, you should use long to receive a pointer.
If you are trying to compile these codes from a Linux terminal, you might get an error saying
expects argument type int
Its because, when you try to get the memory address by printf, you cannot specify it as %d as its shown in the video.
Instead of that try to put %p.
Example:
// this might works fine since the out put is an integer as its expected.
printf("%d\n", *p);
// but to get the address:
printf("%p\n", p);
Building off the above answers, if you had the pointer as a private variable, then you can make a getter function like so:
private int* p;
public int** GetP() { return &p; }
Then when you use it you create a pointer to your class that contains it:
DummyClass* p_dummyClass = new DummyClass;
And then in your use case scenario:
p_dummyClass -> GetP();
(don't forget to deallocate)
static inline unsigned long get_address(void *input){
unsigned long ret;
__asm__(
".intel_syntax noprefix;"
"mov rax, %1;"
"mov %0, rax;"
".att_syntax;"
: "=r"(ret)
: "r"(input));
return ret;
}
Related
after ptr++ pointer does not increment
1 #include<iostream>
2
3 int main() {
4
5 char *ptr;
6 char ch = 'A';
7 ptr = &ch;
8
9 std::cout << "pointer :" << &ptr << "\n";
10 ptr++;
11 std::cout << "pointer after ++ :" << &ptr << "\n";
12 return 0;
13 }
ikar$ g++ pointer_arth.cpp
ikar$ ./a.out
pointer :0x7ffeed9f19a0
pointer after ++ :0x7ffeed9f19a0
ikar$
You're incrementing the pointer, but outputting the address of the variable that holds the pointer itself (&ptr). You should output just ptr (and format it accordingly - see edit below).
Example:
#include <iostream>
int main() {
char data;
char *ptr = &data;
std::cout << "pointer:" << (unsigned long long)ptr << std::endl;
ptr++;
std::cout << "pointer incremented: " << (unsigned long long)ptr << std::endl;
}
Output:
pointer:140732831185615
pointer incremented: 140732831185616
Yes, printing just ptr will output garbage, so I converted the pointer to an integer (since pointers are memory addresses anyway).
As suggested in the comments, you can cast the pointer to void * when printing, which gives nicer formatting:
pointer:0x7ffee5467acf
pointer incremented: 0x7ffee5467ad0
Note how 0x7ffee5467acf == 140732745022159 != 140732831185615 - you'll get different outputs on each run because the kernel will load the executable into different places in memory.
EDIT: yes, the first version of this answer, about simply outputting ptr with std::cout << ptr, was incorrect, because the << operator is overloaded in such a way that it treats pointers to char as C-strings. Thus, that version would access potentially invalid memory and output garbage.
But the concept remains the same. Pointers to int, for example, don't have this "problem" and are printed as hexadecimal numbers, even without casting them to void *: Try it online!. The output shows that pointers are still incremented correctly by sizeof(int), which equals 4 on that machine.
Pointer is incremented successfully in your code.
You print the address of location which hold the pointer variable.
Actually, it is garbage after character -'A' if print 'ptr', you can understand and pointing to such un-handled memory location is not good.
I am a newbie in programming. I have a problem that i can't find an understandable answer by myself. I want to find address of pointer by using C++ and C, but two result are different although they have some similar number. Are they still same address ?
adress of g is :0018F9C4
address of g is: 0018F9D3
This is my code:
#include<iostream>
#include<stdio.h>
void main()
{
char g = 'z';
char*p;
p = &g;
std::cout << "adress of g is :" << &p;
printf("\naddress of g is: %p", p);
}
This line display address of p
std::cout << "address of p is :" << &p;
This line display address in p, ie address of g
printf("\naddress of g is: %p", p);
It's normal to have different result.
Try
std::cout << "address of g is :" << static_cast<void*>(p);
printf("\naddress of g is: %p", p);
On the line with std::cout you print out &p...the address of p itself
On the printf line you print out the value of p..no &p
That's different of course.
You should use
std::cout << "adress of g is :" << (void *)p;
printf("\naddress of g is: %p", p);
And why are you mixing cout and printf?
This example may show it in a better way:
#include<iostream>
#include<stdio.h>
int main()
{
char g = 'z';
char*p = &g;
std::cout << "adress of g is :" << static_cast<void*>(p);
std::cout << "\nadress of p is :" << &p;
return 0;
}
Demo
static_cast<void*>(p) is converting a char* to void* for historical purpose. char* is a pointer but it was used as string in C. So the << operator will deal with it as a value not as a pointer. So the trick here is to convert to another pointer type so the << operator will print its actual value which is the address of g.
Now, &p is the address of p not the address of g. In other word it is the address of the place that the address of g is stored in.
(g=='z') is True
(&g==p) is True
(*p==g) is True
(&p==p) is False
(&g=&p) is False
You need to remember that Address of a pointer and Address of what pointer is pointing to are 2 different thing.
&p --> Address of "P"
p --> Address of "g" what pointer is pointing to
Answer: No, they are not the same address, This is clear as the values are different - A program's memory-address pointing to the same location will always be the same.
Explanation:
(tl;dr - &p is the address of p, not the address of g)
char g = 'z' Does exactly what you'd expect - creates a literal constant, and ensures it will be somewhere in memory during your programs execution.
char*p; p = &g; (which can be shortened to char*p = &g) One again, doesn't what you expect, providing the memory-address of the data g into a variable called p ~ Take note however, that p is also a variable, and thus must be held in memory!
The error in your program is during the last two lines of execution:
std::cout << "adress of g is :" << &p;
printf("\naddress of g is: %p", p);
The first line (using std::cout) will present the address of p, As stated previously, p is a pointer, but a pointer is no different from any other variable - it is simply data stored in memory. As such you are at this point creating a temporary pointer to a pointer - AKA char **.
The second line however, does what you expect, outputting the memory-address stored in p.
A correct program would be as follows.
#include<iostream>
#include<stdio.h>
void main()
{
char g = 'z';
char*p = &g;
std::cout << "adress of g is :" << (int)p; //optionally for C++11 use static_cast<int>
printf("\naddress of g is: %p", p);
}
You could also try using the debugger on this example!
#include<iostream>
#include<stdio.h>
#include<cstdint>
void main()
{
char g = 'z';
char*p = &g;
//THIS ASSUMES 32-bit! Note on 64bit systems a pointer is 64-bit, (you can conclude the result for an 8bit or 16bit addressing model)
uint32_t P_value = (uint32_t)p;
std::cout << "adress of g is :" << P_value;
printf("\naddress of g is: %p", p);
}
When I run the following code:
int i[] = {1,2,3};
int* pointer = i;
cout << i << endl;
char c[] = {'a','b','c','\0'};
char* ptr = c;
cout << ptr << endl;
I get this output:
0x28ff1c
abc
Why does the int pointer return the address while the char pointer returns the actual content of the array?
This is due to overload of << operator. For char * it interprets it as null terminated C string. For int pointer, you just get the address.
The operator
cout <<
is overload 'char *' so it knows how to handle it (in this case, printing all chars till the end one).
But for int is not, so it just prints out the 'memory address'
A pointer to char is the same type as a string literal. So for the sake of simplicity, cout will print the content of the char array as if it was a string. So when you are doing this:
cout << "Some text" << endl;
It does not print the address, the same way as your code is doing.
If you want to pring the address, cast it to size_t
cout << reinterpret_cast<size_t>(ptr) << endl;
basic syntax of pointers: *ptr= &a
here &a will return the memory address of variable a and *ptr will store value of variable a
I want to ask, is it possible to make a pointer return a value from a given memory address? if yes what's the syntax
Yes, you can construct a pointer that refers to some arbitrary address in memory, by initialising the pointer with the address directly, instead of with an expression like &a:
int* ptr = (int*)0x1234ABCD; // hex for convenience
std::cout << *ptr;
Be careful, though, as it is rare that you know such a memory address exactly.
The cast (int*) is required as no implicit conversion exists between int and int*.
Yes. Use the dereference operator *.
For example;
int * a = new int;
int * b = new int;
*a = 5;
// Now a points to a memory location where the number 5 is stored.
b = a; //b now points to the same memory location.
cout << *b << endl; ///prints 5.
cout << a << " " << b << endl; //prints the same address.
int * c = new int;
c = *a;
// Now c points to another memory location than a, but the value is the same.
cout << *c << endl; ///prints 5.
cout << a << " " << c << endl; //prints different addresses.
Why does the following code compile:
int main()
{
int j = 1;
int *jp = &j;
cout << "j is " << j << endl;
cout << "jp is " << jp << endl;
cout << "*jp is " << *jp << endl;
cout << "&j is " << &j << endl;
cout << "&jp is " << &jp << endl;
}
but not this?
#include <iostream>
using namespace std;
int main()
{
int j = 1;
int *jp;
*jp =& j; // This is the only change I have made.
cout << "j is " << j << endl;
cout << "jp is " << jp << endl;
cout << "*jp is " << *jp << endl;
cout << "&j is " << &j << endl;
cout << "&jp is " << &jp << endl;
}
This compiles when I do jp = &j, why? I have only initialized jp in another line, this is not making sense to me.
int *jp;
jp is a pointer. Its value (jp) is a memory address. It points to (*jp) an integer. When you do
jp = &j;
This sets the value to the memory address of j. So now *jp will point to j. When you do
*jp = &j;
This sets the value of the thing jp is pointing to to the memory address of j. When you do:
int *jp;
*jp = &j;
jp is not pointing to anything yet - its value is uninitialized. *jp = &j tries to follow the memory address of the value of jp, which is something random, and set it to &j... which will probably cause a segfault.
To clarify: The * in (int *jp;) is a different one than in *jp = .... The former just declares jp as a pointer. The latter defines how you do the assignment. To make it even more explicit, doing:
int *jp = &j;
is the same as
int *jp; jp = &j;
Note there is no * on the assignment.
*jp = &j;
This right here. Take note of the *. This goes and gets the data pointed to by the pointer, similar to what -> does for objects. What you're doing here is assigning a memory address to an int. The pointer jp points to an int called *jp.
In short, jp is a pointer to an int (therefore an address) and *jp is the int that jp points to. Using &j is getting you the address of j, or a pointer to it.
Change this:
*jp =& j; //this is the only change I have made,
Into this:
jp =& j;
That will make it compile.
The reason int *jp = &j; compiles is because it is declaring and initializing a value. In the non-compiling code, you are doing an assignment. And trying to assign an integer expression (*jp) to a pointer one (&j). Which doesn't make sense at all.
If you do:
jp = &j;
Then it will compile because you are assigning a pointer expression (&j) into a pointer variable (jp). There is type concordance in this case, so it makes sense it is compiling.
*jp =& j; says "write the value of &j to the location that jp points to". This is wrong a) because jp doesn't point to anything and b) because &j is a pointer and the value that jp points to should be an int, not a pointer.
int *jp = &j; declares jp to be an int* (pointer to int), and initialises it with &j (the address of j).
*jp = &j dereferences the pointer to j (giving a reference to j), and then attempts to assign &j to j. This is illegal because j is an int and &j is an int*.
You're parsing it in your head wrong.
The statement:
int *jp = &j;
really ought to be read as:
int* jp = &j;
Resulting in the actins:
declare jp as a pointer to an integer
assign the value of &j to jp
which matches the correction of your second code block:
int *jp;
jp = &j; // This is the only change I have made.
You're getting tripped up by the difference between an initialization and an assignment; the two are different things.
The line
int *jp = &j;
declares jp as a pointer to int and initializes it with the result of the expression &j, which has type "pointer to int" (int *).
The line
*jp = &j;
attempts to assign the result of the expression &j (which has type int *, remember) to the result of the expression *jp (which has the type int1). Since the types of the two expressions don't match, you get a compile-time error.
Note that the fact that jp hasn't been initialized to point anywhere meaningful yet would be a runtime error, not a compile-time error; IOW, if you had written *jp = 5; instead, the program would have compiled just fine (the expressions *jp and 5 have compatible types), but would have (most likely) blown up when you tried to run it.
1 Declarations in C and C++ are based on the types of expressions, not objects. For example, we're declaring jp as a pointer to int. To retrieve the value of the integer being pointed to, we dereference the pointer with the * operator, as in the statement
x = *jp;
The type of the expression *jp is int, so the declaration of the pointer is
int *jp;