I was simply trying out this code which is saw in a tutorial
#include <stdio.h>
int main() {
int a = 34;
int *ptra = &a;
printf("%d\n", ptra);
return 0;
}
Here when I run this code I get a number as an output. The number was 6422216
.
What does this number stand for?
(I was trying to learn pointer arithmetics)
The behavior of the code sample is actually undefined because you pass a value of type int *
where printf
expects an int
as the argument for conversion %d
.
The code may be corrected as printf("%p\\n", (void *)ptra);
or possibly printf("%llu\\n", (long long)ptra);
The value printed is the address of the variable a
, which is system specific and may change from one run of the program to another, as is the case on OS/X that implements address space randomisation to increase the difficulty for hackers to exploit some program flaws.
To cut a long story short, the answer to your question What does this number stand for? is the number is the numeric value of the address of variable a
which is stored in the pointer ptr
. Since addresses can be wider than the int
type, you should use a longer type such as long long
, preferably unsigned:
printf("%llu\n", (long long)ptra);
Your program prints out the memory address of where the integer a is stored and I'll explain why but firstly you need to know what the symbols stand for.
*
- is used to declare a pointer and when placed before a address it will give you what is stored at that address
&
- will give you the address of the variable written after it
So, first you assign the integer a
value of 34
int a = 34;
Then you create a pointer of a integer called ptra
and assign it the memory address of where the integer a
is stored
int *ptra = &a;
And finally you print the value of ptra
which is the memory address of where the integer a
is stored
printf("%d\n", ptra);
If you would wan to print out the value of a through the integer, then you should replace ptra
with *ptra
in the printf function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.