Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Modify Struct/Union/Struct in Called Function

Status
Not open for further replies.

CJason

Programmer
Oct 13, 2004
223
US
How do I pass and use a Struct/Union/Struct into a function, and modify the elements? For example, say I have the following:

struct thestuff {
union {
struct {
char s1[16];
char s2[64];
}s;
char buffer[80];
}u;
}stuff;

How do I pass 'stuff' into a function to be modified?

Thanks so much in advance!!!!
 
Please use [code][/code] tags when posting code.

The better way is to pass a pointer to the structure, like so
Code:
// call this with foo( &stuff );
void foo ( struct thestuff *p ) {
  // here do p->member where you would do stuff.member
}

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Sorry, I'll do the "code" thing from now on.

Salem, I have previously tried what you suggested, but I kept getting errors. Can you show me a quick example, using my struct, that you know works? For example, in void foo, show the members being set. I get errors trying to do something like:

Code:
strcpy(p->u->s->s1,"HELLO");

Am I accessing the structure incorrectly?
 
Yeah, you only need "->" for the first level.
Everything inside the struct/union is "."

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Sweet! Thank you SO much, Salem! I've been trying to figure that out for a LONG time...and "thought" I had tried every combination of "->" and ".". Apparently, I missed this one.

Thanks again!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top