Lion Gordon
Lion Gordon

Reputation: 99

Pointer to pointer issue in C

This is what I'm trying to achieve. Inside pointer 'r' I have the address of pointer 'p', now I try to move the value of 'p'(which is an address) using pointer arithmetic by calling function moveforward(). I get this error :

void value not ignored as it ought to be
movingresult=moveforward(r);

What's wrong here? It's a bit complicated though dealing with pointer to pointer.

#include <stdio.h>

void moveforward(int** y) {
     *y = *y+1;
     printf("value of *y in function : %p\n",*y);

}


int main () {
int a = 16;
int *p;
int **r;
p = &a;
r = &p;
int **movingresult;

printf("Value of p before moving :%p\n",p);
movingresult=moveforward(r);
printf("Value of p after moving :%p",movingresult);

return 0;

}

I just changed my code , so now it looks like this, everything runs well , but the result is not what i expected.

#include <stdio.h>

void moveforward(int** y) {
 *y = *y+1;
 printf("Value of *y now has been moved to : %p\n",*y);

}


int main () {
int a = 16;
int *p;
int **r;
p = &a;
r = &p;
int **movingresult;

printf("Value of p before moving :%p\n",p);
moveforward(r);
printf("Value of p after moving :%p\n",r);

return 0;

}

OUTPUT :
Value of p before moving :0x7fffa5a1c184
Value of *y now after moving : 0x7fffa5a1c188
Value of p after moving :0x7fffa5a1c178

MY EXPECTATION : the 'p' after moving must be equal to *y which is 0x7fffa5a1c188

Upvotes: 2

Views: 75

Answers (2)

Srinidhi Shankar
Srinidhi Shankar

Reputation: 321

This is how things look before doing any pointer arithmetic.

This is how things look before moving the pointer

After you execute moveforward(r);, this is how things look:

After moving the pointer

and these are the pointer values:

printf("Address pointed by p :%p\n",p); // Prints 0x7fffa5a1c188
printf("Address pointed by p :%p\n",*r); // Prints 0x7fffa5a1c188
printf("Address pointed by r :%p\n",r); // Prints 0x7fffa5a1c178

This is because, when you execute the following piece of code,

void moveforward(int** y) {
*y = *y+1;
printf("Value of *y now has been moved to : %p\n",*y);
}

Only the content of pointer p is incremented(0x7fffa5a1c184 to 0x7fffa5a1c188). But the content of pointer r (0x7fffa5a1c178) remains the same.

Upvotes: 1

alex lee
alex lee

Reputation: 21

when you call the function moveforward, the pointer address of r not change. moveforward(r); after call moveforward, the address of r isnot change yet. so if you execute printf("Value of p after moving :%p\n",r);

the address of r are still not change.

if you want get your expected value, you should do: printf("Value of p after moving :%p\n",*r);

Upvotes: 2

Related Questions