Page 2 of 2

Re: Struct?

PostPosted: Thu Oct 25, 2012 1:17 pm
by GEuser
Thanks sky but I've tried all sorts of versions of struct from online research, including example above, no joy thou :(
I've even tried including it as part of a function rather adding as a alone struct. keep getting these errors:

Error line 3: Expected ;
Error line 4: Expected ;

Code used:-
Code: Select all
struct person
{
    int Age = 0;
};

I'll ask on the Linux Subforum

Re: Struct?

PostPosted: Thu Oct 25, 2012 6:22 pm
by Hblade
yeah and GE crashes when using this, if you click "Add" After adding () in front of person

Re: Struct?

PostPosted: Thu Oct 25, 2012 8:17 pm
by skydereign
If you can, try to keep the same questions on the same topic, since there is only one answer. It had nothing to do with linux, just that you can't set initial values for variables within structs. You'd have to create a function for that.

Re: Struct?

PostPosted: Sat Oct 27, 2012 11:04 pm
by SuperSonic
Yeah, so for example:
Code: Select all
struct person
{
    int Age = 0;
}
is illegal, but...
Code: Select all
struct person
{
    int Age;
}

void setAge(struct person PersonStruct, int x)
{
    PersonStruct.Age = x;
}
is perfectly fine :)

Re: Struct?

PostPosted: Sat Oct 27, 2012 11:12 pm
by skydereign
That function won't work properly though. Using that method the function will create a local version of the PersonStruct variable (meaning it will only change the value within the function). You'd have to use a pointer for that.
Code: Select all
struct person
{
    int Age;
};

void
setAge(struct person* PersonStruct, int x)
{
    PersonStruct->Age = x; // notice pointers use -> instead of .
}

And when you call the function, you have to pass the address of the struct.
Code: Select all
struct person test_person;
setAge(&test_person, 18); // &variable gives the address of the variable (a pointer)

Re: Struct?

PostPosted: Sun Oct 28, 2012 1:08 am
by SuperSonic
Oh that's right. I forgot. However, wouldn't it be easier to use a reference parameter? For example:
Code: Select all
struct person
{
    int Age;
};

void setAge(struct person &PersonStruct, int x)
{
    PersonStruct.Age = x;
}
That way when you call the function, you can simply pass the name of the variable instead of the address:
Code: Select all
struct person test_person;
setAge(test_person, 18); // You no longer need the & sign

Re: Struct?

PostPosted: Sun Oct 28, 2012 1:13 am
by skydereign
SuperSonic wrote:I forgot. However, wouldn't it be easier to use a reference parameter?

It would, but you can't do that in C.

Re: Struct?

PostPosted: Sun Oct 28, 2012 3:08 am
by SuperSonic
I'm so sorry. I've forgotten everything I used to know about C :o