How to pass a C ++ link to a C function pointer argument?

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

Should I use the '&' operator address in this call: retCode = MyCFunc (& myVar)? It seems that I am taking a link to a link that 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 higher, it was good until I saw this example on the IBM website (they do not pass using the & 'operator address): 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 that you can do the following:

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

What is right? Should I use the address and the address of the agent in my call or not?

+4
source share
4 answers

Your use is true to do &myVar , to get its address and go to the function that the pointer wants. Accounting for the address of the "link" coincides with the address of the referent.

+3
source

The code you encountered is incorrect. You cannot pass a link to a function that requires a pointer. At least not for int .

+1
source

Actually this:

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

puts the address x in p2 , so you need to.

0
source

Use the & operator. Without this, you are trying to do the wrong conversion of int to int* .

0
source

All Articles