Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pointer and address issue in C

Suppose that in the main function an int type varaible x has a value 20. IF the function is called 2 times as foo(&x) , whats the value of x?

#include<stdio.h> 
void foo(int *n)
{ 
int *m;
m = (int *)malloc(sizeof(int));
*m = 10;
*m = (*m)*5;
n = m;
}
int main() 
{
    int x = 20;
    foo(&x);
    printf("%d",x);
} 

Shouldn’t the value of x be 50 since we are initializing the address of n with m which has the value 50 but its coming out to be 20?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The address of the n pointer is local to foo. So modifying the pointer inside foo has no effect outside of the function. But when dereferencing n, the pointed-to value can be changed.

For x to become 50, the last line of the foo function should have been:

*n = *m;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading