Lots and lots of pointers to structs!

Hi all

This is just a curious question

If i have nested structs that need to be accessed like this inside a function...

struct1->struct2->struct3->data_int = 1;
struct1->struct2->struct3->data_char = 'D';

Is it in any way better to assign the pointer to a variable and use that to access the struct...

random_struct* struct_pointer = struct1->struct2->struct3;
struct_pointer->data_int = 1;
struct_pointer->data_char = 'D';

I understand that this makes code much easier to read and write ( I am accessing the same struct about 10 - 15 times each function ), but does is it actually practical performance wise?

Many thanks, Super_Stinger
Last edited on
My best opinion would say that it would perform about the same. However, a 3 layer nested structure isn't very common. It's usually best to avoid going more than one nest. What is the reason for this nest-ception?
Hi Tresky, cheers for reply

The reason for this intense nest-ception is because im working with a graphics library called SDL ( Simple DirectMedia Layer ). Things like events require you to access event.key.keysym.sym and that would probably be inside another struct.

Note: I am programming in C only, not C++

If maybe theres a better design principle to follow, im all ears open :D!

Another thing also is that i am passing alot of parameters to my functions ( can be up to 8 or 9 args ). I was also constantly having to pass either the screen pointer or event pointer to every function. So i thought why not put it in one struct, so the function can get what it needs from the struct.

Many thanks, Super_Stinger
Last edited on
It's not so much nested structs that you have here as it is a struct that has a member variable that's another struct that has a member variable that's another struct.

The only difference between the two snippets you provided is you create an extra pointer in the latter, which is an additional 4 bytes of memory that your program uses (8 if it's a 64-bit application) temporarily in the scope of whatever function that is. (Although the two snippets might be optimized to the same thing, i'm not entirely sure).
IMO 4 bytes of very temporarily used stack memory is a small price to pay to reduce the code size by a significant amount. I think the days where we had to worry about that insignificant of an amount of memory being used are over far over.
Last edited on
Ahaha, getting tips from the veteran than :P

Cheers for replies, im always looking for better ways to design my code
Topic archived. No new replies allowed.