Pointer and array address - c++

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.

Related

Changing the address of a pointer to edit its value

recently we were trying to use pointer to void, by passing a copy of its address to an instance of a class, in order for the instance to allocate it to the same memory space as an OpenCV Mat it contains, and that is contained in a stack of memory shared by the GPU and CPU to compute it with OpenCV+CUDA.
However while doing that we ran into an issue we didn't quite understand. When passing the address of the pointer to the object, we tried to edit that address so that the pointer was hosted on another space. And while that worked once that copy ran out of scope the value of that pointer returned to being what it was (I'll add a code snip since its confusing to even explain it). However if we accessed the content of the pointer's address that we passed to the function, and edit that, the original pointer is edited.
My hypothesis is that when we passed the pointer's address to the function a copy of the value of that memory address is made, and if that pointer to pointer is edited, the content of it is left undisturbed, while on the other function we accessed the content and directly edited it, hence the copy is left undisturbed and runs out of scope, while the content is edited correctly.
Here is a snip of the code where I try both things:
// Example program
#include <iostream>
#include <string>
void change_value(int **p, int *addr)
{
*p = addr;
}
void change_direction(int **p, int *addr)
{
std::cout << "p value: " << p << std::endl;
std::cout << "p contains: " << *p << std::endl;
std::cout << "p contains contains: " << **p << std::endl;
p = &addr;
std::cout << "p value: " << p << std::endl;
std::cout << "p contains: " << *p << std::endl;
std::cout << "p contains contains: " << **p << std::endl;
}
int main()
{
int a = 1, b = 2, c = 3;
int *ptr = &a;
std::cout << "ptr direction: " << &ptr << std::endl;
std::cout << "ptr value: " << ptr << std::endl;
std::cout << "ptr contains: " << *ptr << std::endl;
std::cout << std::endl;
change_value(&ptr, &b);
std::cout << "change_value" << std::endl;
std::cout << "ptr direction: " << &ptr << std::endl;
std::cout << "ptr value: " << ptr << std::endl;
std::cout << "ptr contains: " << *ptr << std::endl;
std::cout << std::endl;
change_direction(&ptr, &c);
std::cout << std::endl;
std::cout << "change_direction" << std::endl;
std::cout << "ptr direction: " << &ptr << std::endl;
std::cout << "ptr value: " << ptr << std::endl;
std::cout << "ptr contains: " << *ptr << std::endl;
}
This is the output we got. We can see that while ptr is edited on change_value function, since we access to the content of p and edit it, it is not changed on change_direction, since the moment we edit p's address it stops pointing to ptr.
ptr direction: 0x710a27e3fe18
ptr value: 0x710a27e3fe0c
ptr contains: 1
change_value
ptr direction: 0x710a27e3fe18
ptr value: 0x710a27e3fe10
ptr contains: 2
p value: 0x710a27e3fe18
p contains: 0x710a27e3fe10
p contains contains: 2
p value: 0x710a27e3fdd8
p contains: 0x710a27e3fe14
p contains contains: 3
change_direction
ptr direction: 0x710a27e3fe18
ptr value: 0x710a27e3fe10
ptr contains: 2
If anyone could offer a better explanation of what happened I'd be most grateful.
Cheers.
Not sure if I understand the question, but if this:
void change_direction(int **p, int *addr)
{
// ...
p = &addr;
// ...
}
Is supposed to modify the parameter passed to the function, then it isnt correct.
Parameters are passed by value unless you pass them by reference. Passing references is recommended, but if you like you can use pointers. However, then you need to modify what the pointer points to, not the pointer. In the function above p is local to the function. Modifying the value of p has no effect outside the function.
You probably want:
void change_direction(int **p, int *addr)
{
// ...
*p = addr;
// ...
}
Or rather
void change_direction(int *&p, int *addr)
{
// ...
p = addr; // p is a reference, hence no dereference needed
// ...
}
Actually you should prefer int*& here, because a nullptr is not a valid paramter (and thats about the only reason you would use a pointer rather than a reference).
#463035818_is_not_a_number offered a good answer that works well.
But there might be value in fully understanding what your original code is doing.
Beggining from the start:
int a = 1, b = 2, c = 3;
int *ptr = &a;
This initializes three pieces of memory in stack memory containing the int values you gave (a,b,c) and one more piece of memory for your ptr variable that holds the address of a.
You then print out the address and the values of ptr, which obviously doesn't change any of the values.
Next is the call to change_value(int **p, int *addr) which executes.
*p = addr;
The parameter p in this case holds an address to an address to an int somewhere in memory, so *p is the address pointed to by p.
Setting that to addr changes the address p points to.
So in your specific code:
change_value(&ptr,&b);
Sets the value of ptr to be the address of b.
Then next is the change_direction(int **p, int* addr) call (which probably should be named change_address), which executes (ignoring the printing):
p = &addr;
This sets the parameter p to be the address of addr.
But since in C/C++ all functions are called by value (in C there arent even any references, in C++ you have to specify it as #463035818_is_not_a_number mentioned), this doesnt do anything to the original values, that the function has been called with.
So the call:
change_direction(&ptr,&c)
Does not actually change what is held in ptr. At the beginning of the call to the function, the address of ptr (so &ptr) gets copied into a piece of stack-memory, which is then used in the function and freed after the function exits.
I hope this clears things up, pointers can be hard to wrap your head around sometimes.
Cheers.

Pointer Syntax Within Condition

After a pointer is initialized, do you have to use the * dereference operator to call the pointer in a condition?
Example:
int main()
{
int var = 10;
int *ptr = &var;
if(ptr) // does this need to be if(*ptr) ???
{.......}
}
And can I have a short explanation as to why?
Thank you.
if (ptr)
check if the pointer is not Null but
if (*ptr)
check if the value it points to is not zero (in this example is 10)
So for checking the value you shoud add *.
It depends on what you want to do.
if(ptr) checks if the pointer value is nullptr or not. Note that this is shorthand for if(ptr != nullptr).
if(*ptr) checks if what the pointer points to is nullptr (or 0) - and in that case, since you dereference (follow) the pointer to answer the question, the pointer itself had better not be nullptr in that case.
First of all, a pointer is only a variable. However, there are different contexts in which you can use it.
As any other variable you can access the pointers content (which is the adress of the underlying memory) as follows:
int i = 1;
int * p = &i;
std::cout << p << std::endl
this would output the adress of i since this is what is stored in p
If you however want to access the content of the underlying memory (the value of i), you need to dereference the pointer first by using the * operator:
std::cout << *p << std::endl;
This would print the value of iso 1.
of course you can also access the pointer's adress (since the adress of i is a numeric value as well and needs to be stored somewhere too):
std::cout << &p << std::endl;
That would output the adress of p so the adress where the adress of i is stored :)
As a little example try to run this code:
#include <iostream>
int main() {
int i = 1;
int * p = &i;
std::cout << "Value of i(i): " << i << std::endl
<< "Adress of i(&i): " << &i << std::endl
<< "Value of p(p): " << p << std::endl
<< "Dereferenced p(*p): " << *p << std::endl
<< "Adress of p(&p): " << &p << std::endl
<< "Dereferenced adress of p(*(&p)): " << *(&p) << std::endl;
}

What's meaning of &&pointer or &*(pointer_to_pointer) in C++

int *p;
int **pp;
int a = 9;
p = &a;
pp = &p;
cout << "&a: " << &a
cout << "&p: " << &p
cout << "&pp: " << &pp
cout << "pp : " << pp
cout << "*pp: " << *pp
cout << "&*pp: " << &*pp
&&p and &&pp aren't defined in c++ so they are wrong using, but what &*pp is meaning? Is &*pp equalent to &&a?
When the program is starting, the result is as follows:
&a: 00AEFAE4
&p: 00AEFAFC
&pp: 00AEFAF0
pp : 00AEFAFC
*pp: 00AEFAE4
&*pp: 00AEFAFC (=&p ???)
On the other hand, why is &*pp equalent to &p?
you asked what does &*pp means here pp is a double pointer which contains address of the pointer (*p) by writing &*pp firstly you are dereferencing value of **pp
*(pp) which will become value inside pp which is the address of pointer p
by writing &(*pp) now you are trying to get address of the dereferenced value which is (address of p) that will ultimetely become address of p
in simple words where you use both of these operators together they cancel out each other and give you the value present in the pointer
in this case &* will be cancelled out and you will get value of pp which is address of p
i tried to make it as clear as i could.... hope that helps :)

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 .

What is the address that appear when print a pointer without * or &

When print a pointer without * or & shows an address, I don't know what is this address.
For example:
int *n;
int num = 10;
n = &num;
cout << n << endl; // Prints 0020F81C
cout << &n << endl; // Prints 0020f828
The result:
I know cout << &n << endl; to print the address of place in the memory.
But what about cout << n << endl; ?
n is referring to "&num", therefore it's the address to the place in memory where num is pointing to.
You've answered your own question. It is an address. The address in memory of whatever the pointer points to, or zero: in this case, the address of 'num'.
Your second 'cout' prints the address of the pointer itself.