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.
Related
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.
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;
}
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;
}
What happens when I do this? When I remove the first initialization to "boo1", it prints boo2 but now it still prints nothing. Does this mean that the pointer allocate a random memory and assign "boo1" value to it and now I can't access it or what?
string *p;
*p="boo1";
p=new string;
*p="boo2";
cout << *p; //prints nothing
line 1: "p" contains random value, i.e. refers to random memory address.
line 2: random memory block referred by "*p" is interpreted as string instance. This instance is assigned by "boo1".
Try so:
string *p = new string;
*p = "boo1";
cout << *p << '\n';
*p = "boo2";
cout << *p << '\n';
delete p;
Remember that:
std::string is not the same as stupid char[] array!
All pointers must be assigned before usage!
All "new" must have corresponding "delete"!
If you declare a string as pointer ( string *p ), you must allocate memory for it,
so the correct way to do the job is:
string *p = new string;
*p = "boo1";
cout << *p << '\n';
*p = "boo2";
cout << *p << '\n';
The previous answers are correct, however why not using a reference, it seems more convenient in your case.
Something like :
std::string p;
p = "boo1";
std::cout << p << std::endl;
p = "boo2";
std::cout << p << std::endl;
Regards,
Michel.
I have a small problem with using the new and delete operators. I read in a bunch of places that every new operator has to correspond to a delete, and as I understand it, variables created with new will persist until they are hit with that delete. If you would please look at the following code, it's longish but straightforward:
#include <iostream>
using namespace std;
int* testFunction1();
int* testFunction2();
int main(){
int* ptr1 = testFunction1();
int* ptr2 = testFunction2();
cout << *ptr1 << endl; // outputs 5
cout << *(ptr1 - 1) << endl; // outputs random int
cout << *ptr2 << endl; // outputs random int
cout << ptr1 << endl; //prints address of b from testFunction1()
cout << ptr1 - 1 << endl; // prints address of a and c from testFunction1()
cout << ptr2 << endl; // prints address of a and c from testFunction1()
cout << endl;
// delete ptr1; won't work
return 0;
}
int* testFunction1(){
int a = 5, b = 10;
int* pointerToInt1 = new int;
pointerToInt1 = &a;
pointerToInt1 = &b;
cout << &a << endl;
cout << &b << endl;
return pointerToInt1;
}
int* testFunction2(){
int c = 5;
int* pointerToInt2 = &c;
cout << &c << endl;
return pointerToInt2;
}
I have two questions:
I figured that, with testFunction1(), I am returning the pointer by value. But I don't know how to fix that, to return a reference to the pointer, so that I can free the memory in the main method (or for that matter, any other method).
Why did I get 5 as an output when I dereferenced *ptr1? I mean, from the address output, it's clear that the value assigned to c in testFunction2() was stored there, but why did that happen?
Let's don't put your questions aside and explain your code first.
You declare and defined a function named testFunction1 which returns int poitner
int* testFunction1(){
int a = 5, b = 10; // define local variables with initial values. a,b have different memory addresses
int* pointerToInt1 = new int; // dynamic allocate pointer(new address) to int
pointerToInt1 = &a; // set pointerToInt1 to point to address of a
pointerToInt1 = &b; // set pointerToInt1 to point to address of b
cout << &a << endl;
cout << &b << endl;
return pointerToInt1; // return pointerToInt1 pointer which currently points to address of b
}
a,b are local variables inside function testFunction1, they have automatic duration, when function finishes they are release, so pointerToInt1 actually is dangling pointer and access it is undefined behavior.
Also a typical memory leak is introduce in testFunction1, original memory block allocated by new is lost.
int* pointerToInt1 = new int;
pointerToInt1 = &a;
Now, let's "fix" function testFunction1, yup, I mean fix with double quotes.
int* testFunction1(){
int a = 5, b = 10;
int* pointerToInt1 = new int;
*pointerToInt1 = a; // copy a to memory pointerToInt1
*pointerToInt1 = b; // copy b to memory pointerToInt1
cout << &a << endl;
cout << &b << endl;
return pointerToInt1; // return pointerToInt1 pointer
}
After you call function testFunction1, you still need to delete the dynamically allocated memory block.
int *p = testFunction1();
delete p;
Now if you go back and review your two questions, do you get the answer?
You are setting the pointer to a variable allocated on stack:
int a = 5, b = 10;
int* pointerToInt1 = new int; // allocates an int on heap
pointerToInt1 = &a; // overwrite pointer with a local variable
What happens is that the pointer you return points to a value that has automatic allocation on stack so the pinter becomes invalid when the function exits its scope.
In addition, since you lose any reference to the object you allocated dynamically on heap, you can't delete it anymore so it's leaked memory.
Finally the delete tries to delete a pointer which points to an address that was on stack during the call to testFunction1 so it's not a valid pointer anymore, hence delete doesn't work.