Passing pointer to function value not changing [duplicate] - c

This question already has answers here:
Changing address contained by pointer using function
(5 answers)
Closed 4 years ago.
#include<stdio.h>
void foo(int*);
int main()
{
int i = 97, *p = &i;
foo(p);
printf("%d ", *p);
getch();
}
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}
Output is 2 97
Why not 2 2 ?
pointer p holds the address of j now so why 97 is printed ?

You can imagine the function call and its definition the following way. For clarity I'll rename the function parameter as q.
foo(p);
void foo( /*int *q*/ )
{
int *q = p;
int j = 2;
q = &j;
printf("%d ", *q);
}
As it is seen the function parameter (in this case q) is a local variable of the function that is initialized by the value of an argument (in this case by the value of the argument p)
So any changes of the local variable (q) do not influence on the original argument (p).
After exiting the function the local variable will not be alive.
If you want to change the argument itself you should pass it by reference. For example
void foo( int **p )
{
int j = 2;
*p = &j;
printf("%d ", **p);
}
However after exiting the function the original argument/variable p will be invalid because it stores the address of a non-alive local variable of the function j.
So an attempt to access the memory that was occupied by the function's local variable j results in undefined behavior of the program.
You could make the program correct by declaring the local variable j as having static storage duration. For example
void foo( int **p )
{
static int j = 2;
*p = &j;
printf("%d ", **p);
}
and call the function like
foo(&p);

In foo, you assign a new value to p. However this is a copy of the value of p in main, so the change is not visible in main.
If you dereferenced p, then it would change the value if i in main:
void foo(int *p)
{
*p = 2;
printf("%d ", *p);
}

p = &j;
just changes the value of the local variable p. This has no effect on the caller's p variable (because p was passed by value) or the variable that p previously pointed to (because you didn't indirect through it). If you want to change the caller's data, write:
*p = j;

Go through the above code line by line. Here I have written comments as control passes through each of the lines...
#include<stdio.h>
void foo(int*);
int main()
{
int i = 97, *p = &i; //Lets assume i has address 2000
foo(p); //p contains 2000 which is passed to foo. go to foo at 1.
printf("%d ", *p); // when control comes back no change to p it
//still points to 2000 which stores 97
getch();
}
void foo(int *p) 1: // in foo another local variable p is created.
//Let's call this lp. lp has now address 2000. i.e lp
//and p both point to i but one locally exists in a
// function and will be destroyed when control comes out
// of the function
{
int j = 2;
p = &j; // now local p i.e lp points to another var j
// address. Suppose lp has address 3000 now.
printf("%d ", *p); //val at address in lp is 2
}

Related

Pointer to pointer as argument in a function

I have the following code:
void change_adrs(int **q)
{
int * otheraddess;
*q = otheraddress;
}
I can't understand this assignment: *q = otheraddress;
Could anybody help me to explain this. Why can't we use another assignment, such as:
**q = otheraddress;
*q = *otheraddress;
q = &otheraddress;
void change_ptr(int **q)
{
*q = malloc(somemem);
}
void foo()
{
int *ptr;
change_ptr(&ptr);
}
in this example it will change the value of the ptr itself. When you pass a single star pointer you can only change the referenced object.
Look at the assignment of *q = otheraddress; the same as you look at the following:
int x = 4;
int y = x;
you take 2 vairables of the same type and make an assignment between both of them.
In your case, you use the address of int vairables.
int *otheraddress; is a vairable who can get an address (& operator) to int vairable such as:
int x = 4;
int *p = &x; //p<=the address of x
and int **q; can get an address of a vairable which can get int address. such as you 3rd assignment (which should work fine):
int x = 4;
int *p = &x;//p<=the address of x
int **q = &p;//q<=the address of p
for the other assignmets:
**q = otheraddress; you try to assign int* into int**
*q = *otheraddress; you try to assign int into int *
After declaring the variables, * dereferences them.
For example after declaring something like int **a;, when using it we have:
**a value in value in location stored in a(which is ultimately an int)
*a value in location stored in a (which is another location)
a location stored in a
&a location of a itself
Lets take a look and see why each of your examples don't work:
**q = otheraddress; assigning a location to an int ×
*q = *otheraddress; assigning an int to a location ×
Edit: Lets take a look at these two examples:
q = &otheraddress; assigning a location to a location ✓
*q = otheraddress; assigning a location to a location ✓
Lets look at it this way:
Suppose we have:
int *a;
int **q;
in order to prevent segmentation faults in the future, lets first assign some address to a:
int t = 5
a = &t;
Lets look at the addresses afterq = &a:
//first snippet
0x7fffc3a2b338 // &a
0x5596853c98c0 // a
5 // *a
0x7fffc3a2b340 // &q
0x7fffc3a2b338 // q
0x5596853c98c0 // *q
5 // **q
As expected, &a is put into q, and a holds &t, so **(&a) and **(q) will both hold a value of 5.
Now lets look at the addresses after*q = a:
//second snippet
0x7fffc3a2b338 // &a
0x5596853c98c0 // a
5 // *a
0x7fffc3a2b340 // &q
0x7fffc3a2b345 // q
0x5596853c98c0 // *q
5 // **q
Here, a is put into *q, and a itself is &t, so *(a) and *(*q) with both hold a value of 5.
To understand the difference, we look at an example:
int b = 3;
a = &b;
Using this after the first snippet, a is given another address, and q was declared &a(which hasn't changed), therefore **(q) has the same value as **(&a), which is now 3.
This is just like saying:
int a = 3;
int *b = &a;
a = 5; //even though a has changed, b retains its old value of &a, thus *(b) == *(&a) == 5
However on the second snippet, *q was already declared as a before it had changed, so even though a now has a new address, the address inside *q still hasn't changed. Thus trying to access *(*q) will use the old address and give us 5 again.
This is just like saying:
int a = 3;
int b = a;
a = 5; //even though a has changed, b still retains it's old value of 3

Why is the output of the following program 2 97 and not 2 2?

In the following code why doesn't the address of j gets overwritten in p when we call the foo function?
#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&i);
printf("%d ", *p);
}
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}
You are printing with foo - which sets p to 2, then you call a print to p, which is still set to 97 in that scope. foo does not set p globally.
Because p in main is another variable than p in the function. Consequently, even if p is changed inside the function, the value of p in main is still the same and still points to 97.
In more details:
int main()
{
int i = 97, *p = &i; // i is 97 and p points to i
foo(&i);
printf("%d ", *p); // This prints what p points to, i.e. 97
}
void foo(int *p)
{
int j = 2; // Here p still points to i in main
p = &j; // Now p points to j, i.e. the value 2
printf("%d ", *p); // So this prints 2
}
Just to repeat: The important thing is that p in main and p in foo are two different variables.
If you want the program to print 2 2 you can change the function to:
void foo(int *p)
{
int j = 2;
*p = j; // Change this line. This will change i in main
// and thereby also the value that p in main points to
printf("%d ", *p);
}
Below are the steps:
int main()
{
int i = 97;
int* p = &i; // 1. p points to i, i is 97.
foo(&i); // 2. Pass the address of i by value.
printf("%d ", *p); // 6. Print the value of i as neither p nor i have not changed inside foo().
}
// I've renamed the parameter name from p to q for clarity. q is local to
// foo() only; changes made to q are only visible within foo().
void foo(int* q)
{ // 3. q contains a copy of i's address.
int j = 2;
q = &j; // 4. q is set to the address of j.
printf("%d ", *q); // 5. Print the value of j.
}
If you would have done *q = 2 inside foo() you would have changed i's value to 2. That's because q contains the address of i.
The p in main is a different object in memory than the p in foo. Writing to one has no effect on the other. If you want foo to update the value of p in main, then you must pass a pointer to p:
#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&p);
printf("%d ", *p);
}
void foo(int **p)
{
int j = 2;
*p = &j;
printf("%d ", **p);
}
WARNING - doing this will invoke undefined behavior, since p will point to an object that no longer exists - once foo exits, j no longer exists, and p will be an invalid pointer. You may get the output you expect, or you may not.
In order for a function to write to a parameter, you must pass a pointer to that parameter:
void foo( T *ptr )
{
*ptr = new_value(); // updates the thing ptr points to
}
void bar( void )
{
T var; // var is an instance of T
foo( &var ); // have foo update the value of var
}
This is true for any non-array type T, including pointer types. If we replace T with the pointer type P *, we get
void foo( P * *ptr )
{
*ptr = new_value(); // updates the thing ptr points to
}
void bar( void )
{
P * var; // var is an instance of P *
foo( &var ); // have foo update the value of var
}
The semantics are exactly the same - the only thing that's changed is that var starts out as a pointer type.
Things get weird with array types, which we're not going to go into quite yet.

Pointing to a local variable

I would like help understanding this code:
void F (int a, int *b)
{
a = 7 ;
*b = a ;
*b = 4 ;
printf("%d, %d\n", a, *b);
b = &a ;
}
int main()
{
int m = 3, n = 5;
F(m, &n) ;
printf("%d, %d\n", m, n) ;
return 0;
}
I am confused why this does not result in unexpected behavior. At the end of the function F, the value of b is 7. But when I return it is clear that nothing after ' b = &a ' impacts the value of n/b.
I thought that pointing to a local variable would result in garbage/unexpected behavior when the scope changed, but that doesn't appear to be the case.
When you call F, you pass the value of m and the address of n.
In F, b is a pointer to n so that when you change the value of *b, the value of n is changed. However, in "b = &a;" you are changing where b points. After that line, b no longer points to n. Instead, it points to a. That line does nothing at all to the variable n back in main(). After that point, if you change the value of *b, you will change the value of *b and its alias, a. It will not change the value of n in main.
At the end of the function F, the value of b is 7
The value of b is not 7; b is set to point to a, which has the value of 7
But when I return it is clear that nothing after b = &a impacts the value of n
Although b is a pointer, it is passed by value. b inside F behaves as if it were a separate, fully independent, local variable. Any modifications to it made inside F are local to F.
In fact, you cannot trigger undefined behavior in main by actions inside F, because main is not receiving any pointers from F. If you want to make undefined behavior, pass a pointer to pointer into F, and assign it to point to a local variable:
void CauseUB(int a, int **b) {
*b = &a;
}
int main() {
int x = 5, *y = &x;
printf("This is OK: %d\n", *y);
CauseUB(x, &y); // Pointer to pointer
printf("This is UB: %d\n", *y);
return 0;
}
Demo.

Pass by value and pointers

Can you explain why the output is 3?
I was trying to trace the answer and it shows that the line
i+=(a==b?1:0)
gives 1, but doesn't fun1() pass by value so q and p were copied to different variables?
int fun1(int* a, int* b)
{
int i = 0;
i += (&a == &b ? 1 : 0);
i += (a == b ? 1 : 0);
i += (*a == *b ? 1 : 0);
return i;
}
int fun2(int** a, int* b)
{
int i = 0;
i += (a == &b ? 1 : 0);
i += (*a == b ? 1 : 0);
return i;
}
int main(void)
{
int i = 0;
int* p = &i;
int* q = &i;
printf("%d\n", fun1(p, q) + fun2(&p, q));
return 0;
}
In fun1:
(&a==&b?1:0)
This gives 0. They are two different arguments to fun1, basically two different local variables, so they cannot have the same address.
(a==b?1:0)
This gives 1. The values are both &i from main.
(*a==*b?1:0)
This gives 1. Since a and b are equal, they point to the same thing.
In fun2:
(a==&b?1:0)
This gives 0. a and b are both arguments, so a can't equal the address of b (and in fact, it equals &p from main).
(*a==b?1:0)
This gives 1. a is equal to &p from main, so *a is equal to p from main, which is &i from main. And b is equal to q from main, which is again &i from main.
The total is therefore 3.
int fun1(int *a, int*b)
{
int i=0;
i+=(&a==&b?1:0); // 0. &a is the memory where a stands. it's different from &b.
i+=(a==b?1:0); // 1. Both pointers point to the same memory.
i+=(*a==*b?1:0); // 1. *a is the value where it points to, and that's the same as *b.
return i; // returns 2
}
int fun2(int **a, int*b)
{
int i=0;
i+=(a==&b?1:0); // 0
i+=(*a==b?1:0); // 1. *a is the value where it points to, and this is a memory value that is the same as b.
return i; // returns 1
}
That's why it returns 3.
Good question, by the way.
a==b is actually testing whether a and b points to same memory location or not. In function fun1, both a and b points to the same memory location and therefore a==b comes out to be true.
Let's consider at first the first function
int fun1(int *a, int*b)
{
int i=0;
i+=(&a==&b?1:0);
i+=(a==b?1:0);
i+=(*a==*b?1:0);
return i;
}
It was called like
fun1(p,q)
where the both pointers point to the same variable
int *p=&i;
int *q=&i;
So the function got two equal values as its argument. It is the address of variable i.
Function parameters are its local variable. You can imagine the called function like
int fun1( /*int *a, int*b */)
{
int *a = p;
int *b = q;
//...
}
These local variables occupies different extents of memory. So &a is not equal to &b.
As result the value of expression (&a==&b?1:0) will be equal to 0 and variable i in the statement below
i+=(&a==&b?1:0);
will not be changed
The values stored in variables a and b id the address of variable i in main. As it was said early the two variables contain the same value.
So expression (a==b?1:0) will yield 1 and variable i in the statement below
i+=(a==b?1:0);
will be increased.
As the both pointers points to the same object then expression (*a==*b?1:0) also will yield 1. As result variable i will be increased/
i+=(*a==*b?1:0);
The function will return value 2.
Now let's consider the second function
int fun2(int **a, int*b)
{
int i=0;
i+=(a==&b?1:0);
i+=(*a==b?1:0);
return i;
}
As it was said above parameter b is a local variable of the function. Its address does not equal to the address of argument p
So expression (a==&b?1:0) yields 0.
Expression *a is the value stored in argument p The same value is stored in parameter b
So expression (*a==b?1:0) yields 1.
In total the sum of the return values of the functions will be equal to 3.

Why can't I swap memory address of two variables using a function? C

static void swapAddr(int *numOne, int *numTwo)
{
int *tmp;
tmp = numOne;
numOne = numTwo;
numTwo = tmp;
}
int main(void)
{
int a = 15;
int b = 10;
printf("a is: %d\n", a);
printf("Address of a: %p\n", &a);
printf("b is: %d\n", b);
printf("Address of b: %p\n", &b);
swapAddr(&a, &b);
printf("\n");
printf("a is: %d\n", a);
printf("Address of a: %p\n", &a);
printf("b is: %d\n", b);
printf("Address of b: %p\n", &b);
return 0;
}
When I compile and run this piece of code, the output is
a is: 15
Address of a: 0x7fff57f39b98
b is: 10
Address of b: 0x7fff57f39b94
a is: 15
Address of a: 0x7fff57f39b98
b is: 10
Address of b: 0x7fff57f39b94
Clearly the result is not what I intended, since the address does not seem to have been swapped at all.
You generally can't change the address of a variable.
Your 'swapAddr' function changes its parameter values, but these are local to the function - you're not changing anything outside the function. Perhaps the best way of understanding it is that a function parameter always receives a copy of the value that was passed to the function. In this case, you get a copy of the address of a and a copy of the address of b. You can and do change the values of the variables holding those copies (numOne and numTwo), and seeing as they are pointers you could (but don't) change the values that they point at (the values of variables a and b) - but you can't change the addresses of the original variables.
To break it down:
static void swapAddr(int *numOne, int *numTwo)
{
int *tmp;
tmp = numOne;
At this point, tmp and numOne both point to the value of the a variable...
numOne = numTwo;
Now, numOne points instead to the value of the b variable...
numTwo = tmp;
}
And finally, numTwo now points to the value of the a variable. The function returns and numOne and numTwo no longer exist after that point. The addresses of the variables a and b did not change at any stage.
You could however write a function which exchanges the addresses in two pointer variables:
static void swapAddr(int **ptrOne, int **ptrTwo)
{
int *tmp;
tmp = *ptrOne;
*ptrOne = *ptrTwo;
*ptrTwo = tmp;
}
This would allow you to pass the address of two pointer variables, and on return the pointers would be swapped - each one pointing at what the other did previously. But again, this would not change the address of any variable that those pointers happened to point to.
The pointers are passed to the function by value, so changing what they point to isn't going to change the value of the passed parameters in the calling function.
When the function is called, a copy of each pointer is made and saved to the stack. Then the function reads each pointer value off the stack and manipulates them. It never changes the value of the original pointer that was copied onto the stack.
Remember that in C values are passed by value to functions, meaning that the values are copied. When you modify an argument in a function you only modify the local copy inside the function, not the original value that was passed to the function. This goes for pointers as well.
To solve your problem you must pass the arguments by reference, but unfortunately C doesn't have that, it only have pass by value. However, pass by reference can be emulated by passing pointers to the data, just like you do in the function. You must however dereference the pointer to get the values from where the pointers point to, and use those values to do the actual swapping:
int temp = *numOne; // Note: temp is a value not a pointer
*numOne = *numTwo;
*numTwo = temp;
static void swapAddr(int *numOne, int *numTwo)
In this function you are passing 2 pointers by value. This allows you to modify the int pointed to by the pointers but not the pointers themselves.
Use this function definition instead that passes pointers to pointers and allows modifying the pointers themselves
static void swapAddr(int **numOne, int **numTwo) {
int *tmp = *numOne;
numOne = *numTwo;
numTwo = tmp;
}
You could use it like this for example:
int *a = malloc(sizeof(int));
int *b = malloc(sizeof(int));
*a = 15;
*b = 10;
swapAddr(&a, &b);
You canlt change the addresses. The adderss of a is the address of a and that will remain the same until the end of days.
You can do:
static void swapAddr(int **numOne, int **numTwo)
{
int *tmp;
tmp = *numOne;
*numOne = *numTwo;
*numTwo = tmp;
}
int main(void)
{
int a = 15;
int b = 10;
int *pa= &a;
int *pb= &b;
swapAddr(&pa, &pb);
}
What you want to achieve is something like
int *c = &a;
&a = &b;
&b = &a;
This is not possible (you can check: it will not compile). A variable that is created is placed at one place in memory and stays there. So when you create a variable a it will stay variable a and it will not be able to change its identity to that of another variable b.
What you can do is use two pointers int *p1, *p2 to int. These pointers can change their value and point to other objects during lifetime:
p1 = a;
p2 = b;
p1 = b;
p2 = a;
a and b will stay the same, but p1 and p2 can point to different objects over time.
So a thing that would be possible:
static void swapaddr(int **pp1, int **pp2)
{
int *pp;
pp = *pp1;
*pp1 = *pp2;
*pp2 = pp;
}
int main(void)
{
int a = 15, b = 10;
int *pA = &a, *pB = &b;
swapAddr(&pA, &pB);
}
In this example a and b would keep their identity and address, but pA and pB would change their value and pA would point to b and pB would point to pA.
You cannot change the addresses of the variables.however you can change values of pointers,which store addresses as their value,here is an example :
#include <stdio.h>
void swapAddr(int **numOne, int **numTwo)
{
int *tmp;
tmp = *numOne;
*numOne = *numTwo;
*numTwo = tmp;
}
int main(void)
{
int a = 15;
int b = 10;
int *p_a = &a;
int *p_b = &b;
printf("Address of a: %p\n", p_a);
printf("Address of b: %p\n", p_b);
swapAddr(&p_a,&p_b);
printf("\n");
printf("p_a : %p\n",p_a);
printf("p_b : %p\n",p_b);
return 0;
}

Resources