Meraj Hussain Meraj Hussain - 2 months ago 14
C Question

How does int *p = 10; work?

I have a statement

int *p = 10;
. This statement executes perfectly fine on any compiler. I also know that 10 is put in read-only memory. Is there a way i can access this memory. How can I print this on console? The statement
printf("%d",*p)
crashes. How can I make it print on console.

Edit

int main()
{
int *p = 10;
}


the above code compiles fine and runs fine.

int main()
{
int *p = 10;
printf("\n%d",*p); //crashes
}


the above code gives segmentation fault. I wanted to know more explanation on this?

Answer

By typing int *p = 10; you say to compiler:

Lets have a pointer on integer, called "p". Set p to 10 => p points on address 10 on memory.

By typing printf("%d",*p); you say to compiler:

Show me -as a integer- what is at the address 10 on memory.

The code

int *p = 10;

Is equivalent to:

int *p;
p = 10; 

Is not equivalent to:

int *p;
*p = 10; 

Corrected code could be:

// define an integer
int i;
// define a pointer on the integer
int *p = &i;
// set integer to 10, through pointer
*p = 10;

// display integer through pointer
printf("%d",*p);