#include<stdio.h>
#include<string.h>
void fn (int *ptr)
{
static int val=100;
ptr=&val;
}
main()
{
int i=10;
printf("%d", i);
fn(&i);
printf("%d", i);
getch();
}

The output of the above code is 10 10.
why not 10 100?
What is happening inside fn?

Dani AI

Generated

The result is 10 10. is correct: the pointer parameter is a local copy, so changing that pointer inside fn does not change the caller's variable.

When you call fn(&i) the function receives a copy of the address of i. Assigning a different address to that local copy only rebinds the local variable; it does not write to the memory i occupies. To change the value of i from inside the function you must store through the pointer (for example, *ptr = 100;). That writes to the object the original pointer referred to and will be visible after the function returns.

If the goal is to make the caller’s pointer itself point somewhere else (for example, make the caller’s pointer refer to a static value inside the function), you must pass a pointer-to-pointer. For example, accept int **pp and do *pp = &static_val; (the static storage makes the address safe to hold after return). By contrast, returning the address of an automatic (non-static) local would produce a dangling pointer.

Practical notes: static gives a lifetime that spans the program, so taking its address is safe outside the function; getch() and an implicit main() return are nonportable or obsolete — prefer int main(void) and portable I/O. In short: reassigning the formal pointer parameter does not alter the caller’s i, which is why you see 10 then 10.

ptr is being given a new address, in the assignment statement ptr=&val, in fn(). It no longer has anything to do with i.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.