Home > Blockchain >  Confusion of ptr address after passing to a function
Confusion of ptr address after passing to a function

Time:12-20

When a ptr is passed to a function, how to ensure its address is not changed? See the following cope snippet. Is it possible to make this function inline and achieve the goal?

void test(int *p) {
    printf("%p\n", (void*)&p);
}

int main(void) {
  int a = 10;
  int *p = &a;
  printf("%p\n", (void*)&p);
  test(p);
  return 0;
}

Output is

0x7ffe53b10938
0x7ffe53b10940

Edit: the goal is that I want to maintain the same address in main and test when manipulating the variable p.

CodePudding user response:

It will be easier to understand if you add more prints.

void test(unsigned *pFunc) {
    printf("Address of pFunc %p\n", (void*)&pFunc);
    printf("Address held by pFunc %p\n", (void*)pFunc);
    printf("Object referenced by pFunc: 0x%x\n", *pFunc);
}

int main(void) {
  unsigned a = 0x10203040;
  unsigned *pMain = &a;
  printf("Address of pMain %p\n", (void*)&pMain);
  printf("Address held by pMain %p\n", (void*)pMain);
  test(pMain);
  return 0;
}

https://godbolt.org/z/9a74E4nnK

Result:

Address of pMain 0x7fff2161ff30
Address held by pMain 0x7fff2161ff44
Address of pFunc 0x7fff2161ff38
Address held by pFunc 0x7fff2161ff44
Object referenced by pFunc: 0x10203040
  1. pFunc is a variable local to function test. It has its own address and it holds the address kept in the pMain variable
  2. pMain is a variable local to function main. It has its own address and it holds the address of the a variable.

As you see the both pointers have the same value - which is the address of the a variable.

If you want the pFunc pointer to holds the address of the pMain variable you need to declare it as pointer po pointer:

void test(unsigned **pFunc) {
    printf("Address of pFunc %p\n", (void*)&pFunc);
    printf("Address held by pFunc %p\n", (void*)pFunc);
    printf("object referenced by *pFunc %p\n", (void*)*pFunc);
    printf("Object referenced by pFunc: 0x%x\n", **pFunc);
}

int main(void) {
  unsigned a = 0x10203040;
  unsigned *pMain = &a;
  printf("Address of pMain %p\n", (void*)&pMain);
  printf("Address held by pMain %p\n", (void*)pMain);
  test(&pMain);
  return 0;
}

Result:

Address of pMain 0x7ffda335b9a8
Address held by pMain 0x7ffda335b9a4
Address of pFunc 0x7ffda335b998
Address held by pFunc 0x7ffda335b9a8
object referenced by *pFunc 0x7ffda335b9a4
Object referenced by pFunc: 0x10203040
  • Related