PDA

View Full Version : [SOLVED] C strange struct



conehead77
December 16th, 2010, 11:11 PM
Hi,

i'm quite new to C and i encountered following code snippet:


struct prefix_ipv6 *
prefix_ipv6_new (void)
{
struct prefix_ipv6 *p;

/* Allocate a full-size struct prefix to avoid problems with structure
size mismatches. */
p = (struct prefix_ipv6 *)prefix_new();
p->family = AF_INET6;
return p;
}

I only know "normal" structs like this:


struct mystruct
{
int int_member;
double double_member;
char string_member[25];
} variable;


What does the first version do? It seems like there is a function inside the struct? But i don't really get it. Also does anybody have a good suggestion for a more advanced C book?

Decatf
December 16th, 2010, 11:17 PM
The function prefix_ipv6_new returns a pointer to a prefix_ipv6 struct.

The line p = (struct prefix_ipv6 *)prefix_new(); is just calling a function prefix_new() and casting the return value to a prefix_ipv6 pointer.

trent.josephsen
December 16th, 2010, 11:20 PM
That's not a struct definition -- it's a function definition. The definition of struct prefix_ipv6 should look very like your example.

That beside the point, this is very simple in terms of syntax. If you couldn't figure that out on your own, I doubt you're ready for anything that could be called "advanced C". Re-read your copy of K&R2 (you do have one, surely?) and do all the exercises you skipped the first time.

StephenDavison
December 16th, 2010, 11:22 PM
struct prefix_ipv6 *
prefix_ipv6_new (void)
{
struct prefix_ipv6 *p;

/* Allocate a full-size struct prefix to avoid problems with structure
size mismatches. */
p = (struct prefix_ipv6 *)prefix_new();
p->family = AF_INET6;
return p;
}Let's see, it's been many years since I've looked at C, but here goes...
prefix_ipv6_new() is a function that accepts no parameters and returns a pointer to a prefix_ipv6 structure. In that function, p points to a dynamically allocated prefix_ipv6 structure. p->family is the family element in the structure pointed to by p, and it is assigned the value AF_INET6. So, what you are looking at is a function not a struct.

AFAIAC, if you only buy one book on C make it the the K&R book, The C Programming Language.

Edited to add: he he, looks like Trent and Decatf got to it while I was typing. Good to see the K&R book still rules.

conehead77
December 16th, 2010, 11:31 PM
Ah, thank you all. I guess my brain needs some adjustment to read C code. And thanks for the book suggestion, i'll check it out for sure.