Home > OS >  Pointer and address issue in C
Pointer and address issue in C

Time:12-12

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?

CodePudding user response:

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;
  • Related