Structure Question

Jun 21, 2009 at 10:28pm
Is it a fix rule that when we use a structure, we have to follow this syntax

struct_key word struct_name
{
type_name member_names
}

struct_type_name name_of_variable = {values}

The question is whether it is ok just to initialize

struct_type_name name_of_variable = constant

so this is what it is:
1
2
3
4
5
6
7
struct price
{
     int x;
     int y;
}

price apple = 6;


if so why and if not why not?
Jun 21, 2009 at 10:50pm
Your syntax is off; I would suggest checking over it again. Assuming you are using C, you also need to prefix the type names with the word struct unless you use a typedef.
Jun 21, 2009 at 10:53pm
I posted here before and my post totally didn't answer your question at all XD Sorry about that. For some reason I thought you were asking a completely different quesiton.

ANYWAY:

 
price apple = 6;


This does not work. The reason for this is because 6 is type 'int' and not type 'price', and the compiler has no idea what you're trying to do by assigning that.
Jun 22, 2009 at 12:32am
Try something like:

1
2
3
4
5
6
7
8
9
10
struct price{
int apple;
int pineapple;
int pear;
int orange;
} price, amountofmoneyneededtobuy;

price.apple = 5;
price.pear = 9;
amountofmoneyneededtobuy.orange = 8;


That should work i think.
Jun 22, 2009 at 2:20am
Disch that's OK and I just wanna know if we could add value to the object of the structure but pether has eliminated my doubt. Because the book always use sort of like the array stuff for the structure, that really pigues me to ask such a question.

But how come pether's code work? because of the member of apple which has been defined as type int?

1
2
3
4
5
6
7
8
9
10
struct price{
int apple;
int pineapple;
int pear;
int orange;
} price, amountofmoneyneededtobuy;

price.apple = 5;
price.pear = 9;
amountofmoneyneededtobuy.orange = 8;
Jun 22, 2009 at 2:56am
Yes, by price.apple = 5 You are accessing the struct price called price's apple value and setting it to 5. Read up on the '.' operator/classes:

http://www.cplusplus.com/doc/tutorial/classes/
Jun 22, 2009 at 8:02am
An additional issue...

Declaring fruits as integers in the class "price" gives me strange feelings...:P What is your program supposed to do?
Jun 22, 2009 at 11:48am
Read this in the cplusplus.com guide;

http://www.cplusplus.com/doc/tutorial/structures/
Jun 22, 2009 at 12:28pm
The question is whether it is ok just to initialize

struct_type_name name_of_variable = constant


If you provide a constructor which takes one integer as argument to the struct, you can:
1
2
3
4
5
6
7
struct price
{
     int x;
     int y;
     price ( int value ) : x ( value ), y ( value ) {} // assign both x and y to 'value'
};
price apple = 6; // apple.x and apple.y are set to 6 

Last edited on Jun 22, 2009 at 12:28pm
Topic archived. No new replies allowed.