Pointers Basic : A simple query - c++

I am new to cpp and learning pointers. while practicing the codes i came across this. When i do &(a pointer), it gives an another memory location.i want to know what this address is. I assume its the location where the ptr is saved. it has to be saved somewhere though it has the memory of value variable.
#include<iostream>
using namespace std;
int main()
{
int v =6;
int *ptr;
ptr = &v;
cout << "1: " << ptr << endl;
cout << "2: " << *ptr << endl;
cout << "3: " << &ptr << endl;
return 0;
}
OUTPUT:
1: 0x29cc6c
2: 6
3: 0x29cc68

Correct.
Output 1 is the value of the pointer, which is the address that it points to.
Output 2 is the "dereferenced" pointer which means it is the value contained at Output 1 (the location the pointer is pointing to).
Output 3 is the location where the pointer (which contains the value from output 1) is being stored.

You got it perfectly right:
v is a variable, so &v is the adress where v is stored in memory;
ptr is a variable as well, so &ptr is the adress where ptr is stored in memory.
In your example, because these variables are stored one after the other (on the local stack), their adresses are only 4 bytes apart.

Related

Why do my pointers print different addresses? [duplicate]

#include <iostream>
using namespace std;
int main() {
int* z = new int(9);
cout << "address: " << z << endl;
cout << "value: " << *z << endl;
cout << "referance: " << &z << endl;
return 0;
}
Looking at the cout values, I was expecting the address and reference to give the same address, but heres what the output is:
address: 0x7fc452c032a0
value: 9
referance: 0x7fff5191b8d8
Just curious about the reason for this, is the plain value(z) the address of the variable in the heap with a value of 9, where var(&z) is address of the pointer variable which is located in the stack?
Here is a visualization:
Is the
&z designates the adress of the pointer int * z where you store the allocated adress new int(9).
The pointer z and the value 9 are stored at two different locations in memory.
There is not any notion of reference here, only adresses.
Let me go through some of the basics first.
A variable is a name that is used to refer to some location in the memory, a location that holds a value with which we are working.
Using '&' in C/C++ we can get the address of the variable.
A pointer is a variable that stores the address of a variable. For instance, in the example you are referring to
int* z = new int(9);
variable z stores the address of the value 9 [new int(9)].
Now, finally this variable has to be stored at some location in the memory and this can be accessed using ampersand (&).
&z //gives the address of the pointer to value 9 (address of variable z).
This is the same way the pointers and pointers to a pointer (multi level pointers) works.
int* z;
Above statement implies a pointer variable of int type declaration.
int* z = new int();
Above statement implies an address is allocated to pointer variable of int type dynamically.
int* z = new int(9);
Above statement implies value 9 is stored in a dynamically allocated.
cout << "address: " << z << endl;
Above line of code tells the address of pointer variable z.
cout << "value: " << *z << endl;
Above line of code tells the value stored in the variable z.
cout << "referance: " << &z << endl;
Above line of code tells the dynamically created variable's address.

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.

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.

char pointer doesn't increment?

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.

Pointer variable, differences in var and &var

#include <iostream>
using namespace std;
int main() {
int* z = new int(9);
cout << "address: " << z << endl;
cout << "value: " << *z << endl;
cout << "referance: " << &z << endl;
return 0;
}
Looking at the cout values, I was expecting the address and reference to give the same address, but heres what the output is:
address: 0x7fc452c032a0
value: 9
referance: 0x7fff5191b8d8
Just curious about the reason for this, is the plain value(z) the address of the variable in the heap with a value of 9, where var(&z) is address of the pointer variable which is located in the stack?
Here is a visualization:
Is the
&z designates the adress of the pointer int * z where you store the allocated adress new int(9).
The pointer z and the value 9 are stored at two different locations in memory.
There is not any notion of reference here, only adresses.
Let me go through some of the basics first.
A variable is a name that is used to refer to some location in the memory, a location that holds a value with which we are working.
Using '&' in C/C++ we can get the address of the variable.
A pointer is a variable that stores the address of a variable. For instance, in the example you are referring to
int* z = new int(9);
variable z stores the address of the value 9 [new int(9)].
Now, finally this variable has to be stored at some location in the memory and this can be accessed using ampersand (&).
&z //gives the address of the pointer to value 9 (address of variable z).
This is the same way the pointers and pointers to a pointer (multi level pointers) works.
int* z;
Above statement implies a pointer variable of int type declaration.
int* z = new int();
Above statement implies an address is allocated to pointer variable of int type dynamically.
int* z = new int(9);
Above statement implies value 9 is stored in a dynamically allocated.
cout << "address: " << z << endl;
Above line of code tells the address of pointer variable z.
cout << "value: " << *z << endl;
Above line of code tells the value stored in the variable z.
cout << "referance: " << &z << endl;
Above line of code tells the dynamically created variable's address.