Pointer passing

Q

quigstah

Hey All:

Any insight you could give me would be tremendously appreciated.

I have a data structure, one element of which takes the form:

struct.struct.ptr

Where ptr is a pointer to a struct. I initialize that ptr to NULL in
main(), and then pass the pointer as such to another function for
initialization:

init(struct.struct.ptr);

The init() prototype is as such:

init(mytype_t *ptr);

Clearly I'm doing something wrong: while ptr is correctly initialized
in init(), when I try to use it back in main() it's still NULL. How do
I correctly pass ptr such that it is properly made available after
initialization?

Thanks!

Regards,
John Quigley
 
R

Richard Heathfield

(e-mail address removed) said:
init(struct.struct.ptr);

The init() prototype is as such:

init(mytype_t *ptr);

Clearly I'm doing something wrong: while ptr is correctly initialized
in init(), when I try to use it back in main() it's still NULL.

C is a pass-by-value language.
How do
I correctly pass ptr such that it is properly made available after
initialization?

Instead of passing its value, pass a value that represents its address.

void init(mytype_t *ptr) { *ptr = whatever; }

init(&this.that.ptr);
 
Q

quigstah

Richard,

Thank you kindly for your quick response.
init(&this.that.ptr);

Okay, I have tried doing this in the past. However, I get the
following warning at time of compilation:

warning: passing argument 1 of 'init' from incompatible pointer type.

I need to run, but will continue to look into this a bit later today.
Any thoughts as to why I would be getting this warning would help
tremendously. Thanks again.

Regards,
John Quigley
 
R

Richard Heathfield

(e-mail address removed) said:
Richard,

Thank you kindly for your quick response.


Okay, I have tried doing this in the past. However, I get the
following warning at time of compilation:

warning: passing argument 1 of 'init' from incompatible pointer type.

That's because I said:

void init(mytype_t *ptr) { *ptr = whatever; }

but should have said:

void init(mytype_t **ptr) { *ptr = whatever; }

Note the extra *. Sorry about that.
 
K

Keith Thompson

Richard,

Thank you kindly for your quick response.


Okay, I have tried doing this in the past. However, I get the
following warning at time of compilation:

warning: passing argument 1 of 'init' from incompatible pointer type.

You need to change both the call (so it passes a pointer-to-pointer)
and the function (so it expects a pointer-to-pointer). You also need
to change the body of the function so it operates on a
pointer-to-pointer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,184
Messages
2,570,973
Members
47,529
Latest member
JaclynShum

Latest Threads

Top