Address of pointer - c++

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);
}

Related

Pointers and references

I am currently learning c++ and pointers inside of c++. I am curious as to why I get a different memory address when I reference a pointer and why it isn't the same as the reference to the variable. Here is my super simple code:
#include <iostream>
using namespace std;
int main() {
int n = 50;
int *p = &n;
cout << "Number: " << n << endl;
cout << "Number with &: " << &n << endl;
cout << "Pointer: " << p << endl;
cout << "Pointer with *: " << *p << endl;
cout << "Pointer with &: " << &p << endl;
}
Why does &p give me a different address than "&n" and "p"? Thank you
First you declare an int variable n with the value of 50. This value will be stored at an address in memory. When you print n you get the value that the variable n holds.
Then you declare a pointer *p pointing to the variable n. This is a new variable that will hold the address to the variable n, where it is stored in memory. When you print p you will get back that address.
You can also ask for the address to where the value of n is stored by using the & symbol. This is what you get when you print &n, this will be the same as the pointer p.
Using the * symbol before a pointer will dereference it, meaning instead of returning the address that is the pointer, it will return the value that the pointer is pointing to. In your case this is an int with the value 50.
Lastly, the pointer *p that you declared is stored at it's own address in memory. Just as you could get the address to the variable n with the & symbol, you can get the address of p by using &p. This will be different from the address of n since it's not where 50 is stored, it's where the pointer to the value 50 is stored.

returning the address of a pointer

I'm trying to return the address of a pointer using the code below:
#include <iostream>
using namespace std;
int main(){
int x = 5;
int *p = &x;
//int **pp = &p;
cout << &p << endl;
return 0;
}
However what gets printed is 0x28fea8, which is the same address as x itself. Now if I uncomment the only commented line above and leave everything else as is, then what gets printed is 0x28fea4 which seems to be the correct address of the pointer.
My question is why do I need the uncommented line in order to display the correct address of my pointer?
Why do "cout << p << endl" and "cout << &p << endl" both display 0x28fea8 if that line is left commented?
Shouldn't "cout << &p << endl" display 0x28fea4 regardless of the other line?
I'm using Qt Creator as my compiler/ide if that helps. I downloaded my compiler from the following link: http://web.stanford.edu/~rawatson/qt/windows_install/index.html
EDIT: Ok how silly of me. My issue was that I was comparing addresses by changing values and then re-running the program. Instead I should have compared by printing them all in one program run. When I compare in one program I get different addresses for p and &p, as it should be.
I'm unable to reproduce what you are telling, with this code:
#include <cstdio>
using namespace std;
int main() {
int x = 5;
int* p = &x;
printf("x address: %p\n", &x);
printf("p value: %p\n", p);
printf("p address: %p\n", &p);
return 0;
}
I get the following output:
x address: 0xbfd6bba8
p value: 0xbfd6bba8
p address: 0xbfd6bbac
which is correct and indeed &p is &x+4 which is correct on a 32bit architecture since they are allocated on stack.
int x = 5;
int *p = &x; // b stores addres of variabile a
cout << "Adress of x is : " << p <<endl; // printing the adress of a
cout << "Value of x is : " << *p << endl; // printing the variabile stores in a
int **pp = &p; // pp stores thea adress of p
cout <<"Adress of p is" << pp << endl; //printing the adress of p
cout << "Adress of x is" <<*pp << endl; //printing the adress of x
return 0;
I hope that the comments solve your problem .

Pointer to a given memory address -C++

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.

How to get address of a pointer in c/c++?

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;
}

Pointer and array address

I was just playing with pointers and found this weird thing. I created the pointer p and displayed its address as I did in the following program, the address of p and &p is different, why are they different?
int main()
{
int *p, s[5];
cout << p <<endl;
cout << &p <<endl;
p = s;
cout << p <<endl;
cout << &p <<endl;
}
P is a pointer that means it holds an address to an integer. So when you print p it displays address of the integer it points to. Whereas when you print &p you are actually printing the address of p itself rather than the address it points to.
As Jeeva said, pointer p also occupies a part of memory(the yellow part in this pic, its address is 0x300) and in this area, it holds the value which is the address of the array s. So p == 0x100 and &p == 0x300
If p were equal to &p, the pointer would point to itself, which is only possible with void pointers:
void* p = &p;
assert(p == &p);
I have yet to see a practical use for this, though :)
Oh wait, it also happens in self-referencing recursive data structures, which can be quite useful:
struct X
{
X* p;
void print()
{
std::cout << " p = " << p << '\n';
std::cout << "&p = " << &p << '\n';
}
};
X x;
x.p = &x;
x.print();
Think linked container, where the last node has itself as its successor. Output on my system:
p = 0x7fffb4455d40
&p = 0x7fffb4455d40
Why? Because an object usually starts at the same address in memory as its first data member.