tags:

views:

119

answers:

2

This is a simplified example of the problem I have:

#include <stdio.h>
#include <stdlib.h>

void f2(int** a) {
  printf("a: %i\n", **a);
}

void f1(int* a) {
  f2(&a);
}

int main() {
  int a = 3;
  f1(&a); // prints "a: 3"

  f2(???);

  return 0;
}

The problem is that I would like to be able to use f2() both in main() and in f1().

Can that be done without using global variables?

+9  A: 

You need to pass a pointer to a pointer, so you need to create a pointer in main() so that you can take its address:

int main() 
{
    int a = 3;
    int* aptr = &a;
    f2(&aptr);

    return 0;
}
James McNellis
Awesome trick! Thanks =)
Louise
+4  A: 
int main() {
  int a = 3;
  int *aa = &a; /* stores the address of a */

  f1(&a);  /* prints "a: 3" */
  f2(&aa); /* prints "a: 3" */

  return 0;
}
Forest