PDA

View Full Version : Pointer confusion ... parameter problems


LiquidG
08-02-2002, 01:02 PM
After several a printf command, I've come along something very strange in my code ... I have a couple functions, as follows:


foo1()-- returns a value for a built in data type

foo2() -- returns a pointer to an array of values of the same built in data type as above (lenth of array passed as param)

foo3() -- prints out the array, under specified format


The problem that i'm having is in my main() function, i'm calling foo2, which in turn calls foo1 ... the output is as expected. But, when i call foo3, and pass to a pointer that foo2 returns, a printf of the passed parameter shows that its been altered! ... no where else in my code to i write to the array, and when i do my printf calls to verify the outputs, i make sure to do so by assigning a temp var first to equal the param/return in question.

Any suggestions? I'm assuming that I'm forgetting something bout ptr access in C, and I come from a humble C++ ... so my C is a little shakey right now.

sans-hubris
08-02-2002, 02:10 PM
C++ is a superset of C, and pointers haven't really changed all that much in the transition.

Can you show us some code or an approximation of what it looks like?

stuka
08-02-2002, 02:50 PM
I think your problem probably lies in foo2() - you say you return a pointer to an array of your ADT. If this array was an automatic variable inside the function, that's your problem right there. Typically, in C, if you want to create dynamically allocated structures (like arrays, etc) and pass pointers to them back to the caller, you do something like this:int foo2(mydata **ptr, int len){
(*ptr) = (mydata*)malloc(sizeof(mydata) * len);
/*initialize data*/
return 0; /*return code indicates error status if desired*/
}

LiquidG
08-02-2002, 04:17 PM
Originally posted by Stuka
I think your problem probably lies in foo2() - you say you return a pointer to an array of your ADT. If this array was an automatic variable inside the function, that's your problem right there. Typically, in C, if you want to create dynamically allocated structures (like arrays, etc) and pass pointers to them back to the caller, you do something like this:int foo2(mydata **ptr, int len){
(*ptr) = (mydata*)malloc(sizeof(mydata) * len);
/*initialize data*/
return 0; /*return code indicates error status if desired*/
}

:clap: very nice ... thank you ... all it took was one malloc call to allocate some space for the array, and it works as intended now.

I appreciate the speedy replies from everyone as well ... this is by far the fastest (and most useful) forum for coding issues that I've seen, especially without torched for asking what seems to be a stupid question :biggrin:

stuka
08-05-2002, 12:13 AM
Glad I could help!