4

I just want to check here on how to pass a reference to a function that wants a pointer. I have a code example below. In my case, I am passing a C++ reference to a C function that will change my value.

Should I use the '&' address of operator in this call: retCode=MyCFunc( &myVar)? It seems that I am taking a reference of a reference, which is not allowed in C++. However, it compiles fine and seems to work.

MainFunc()
{

    int retCode = 0;
    unsigned long myVar = 0;

    retCode = MyCPlusPlusFunc(myVar);

    // use myVars new value for some checks
    ...
    ...
}

int MyCPlusPlusFunc( unsigned long& myVar)
{
  int retCode = 0;
  retCode=MyCFunc( &myVar);
  return retCode;  
}

int MyCFunc ( unsigned long* myVar) 
{
  *myVar = 5;
}

I thought my code was above was fine, until I saw this example on the IBM site (they do not pass using the '&' address of operator): http://publib.boulder.ibm.com/infocenter/zos/v1r11/index.jsp?topic=/com.ibm.zos.r11.ceea400/ceea417020.htm

// C++ Usage
extern "C" {
  int cfunc(int *);
}

main()
{
  int result, y=5;
  int& x=y;

  result=cfunc(x); /* by reference */
  if (y==6)
  printf("It worked!\n");


// C Subroutine
cfunc( int *newval )
{
  // receive into pointer
  ++(*newval);
  return *newval;
}

In general, I know you can do the following:

int x = 0;
int &r = x;
int *p2 = &r; //assign pointer to a reference

What is the correct? Should I use the & address of operator in my call or not?

3
  • Please fix your code using the appropriate button in the edit form. Commented Dec 6, 2010 at 17:40
  • Thanks... looks much better now! Commented Dec 6, 2010 at 17:43
  • <quote>//assign pointer to a reference</quote> Not true. In this case p2 points at x. How the IBM one compiles is a mystery to me. It generates about 20 compile time errors. Commented Dec 6, 2010 at 22:46

4 Answers 4

3

Your usage is correct, to do &myVar to get the address of it and pass to a function that wants a pointer. Taking the address-of a 'reference' is the same as taking the address of the referent.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Just wanted a sanity check after seeing the code example in that IBM link.
1

The code you came across is wrong. There is no way you can pass a reference to a function that requires a pointer. At least, not for int.

1 Comment

Yeah, you are right. Just wanted to make sure I wasn't going crazy. Thanks!
0

Actually this:

int x = 0;
int &r = x;
int *p2 = &r;

puts into p2 the address of x, so it's what you need.

Comments

0

Use the & operator. Without it you are attempting an invalid conversion of int to int*.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.