问题描述:

I am using a library developed in C (particularly: HTK). I've made a bit modifications to source and trying to get a pointer (to beginning of a linked list) from a function.

Not to go into too much detail; say I have a struct named OutType. In my C++ code I declare:

OutType* Out; and pass it to some function LName(....., OutType* Out)

Now, in the C library, LName takes parameter Out, and calles a function named SaveH where Out is the return value (Out=SaveH(...)) and in SaveH, Out is malloc'ed as OutType returnOut=(OutType*)malloc(1,sizeof(OutType));

As far as I see, Out is perfectly malloc'ed, and in LName function I can get the address of the memory area that was allocated. But when I return to my C++ code, where I call LName and pass Out as a parameter, that parameter always has 0 as the address.

If I leave everything same, but just change SaveH so that Out is not a return value, but a parameter as SaveH(....,OutType* Out) and alloc that value in C++ code before passing everything is fine.

Is it normal? Is there some problem with pointer allocated in C library, using in C++ code?

Thanks

网友答案:

You are passing a copy of the pointer, which is why the change in the C library isn't seen in your C++ code.

Since you're already modifying the library, you should have that C function take a pointer to a pointer.

LName(....., OutType** Out)

*Out=SaveH(...);

Now you'll be passing the address of the C++ pointer, so your C code will be modifying the same original pointer.

网友答案:

If you have a function:

void Foo( int * p ) {
   p = malloc( sizeof(int) );
}

then when you call it:

int * x;
Foo( x );

the value of x will be unchanged, because a copy of the pointer is taken. You need a pointer to a pointer:

void Foo( int ** p ) {
   *p = malloc( sizeof(int) );
}

then:

int * x;
Foo( & x );

If this is not your problem, post some actual code that illustrates what you are asking about.

相关阅读:
Top