Click to See Complete Forum and Search --> : c structs question


phyte
12-20-2002, 01:45 PM
//structures

#include <stdio.h>
struct cars{
int year;
char model[15];
int engine_power;
float weight;
};

int main(){

struct cars van;
van.year=1998;
//gets(van.model);
van.model="TOYOTA";
van.engine_power=500;
van.weight=34.3;

printf("Year:%d\tModel:%s\tCC:%d\tWeight:%f\n",van.year,van.model,van.engine_power,van.weight);




return 0;
}

I get an error when i compile my code...Theres a snippet above..

The error is:
structs.c: In function `main':
structs.c:16: incompatible types in assignment

Why can't i initialize the van.model value this way?

If i use something like gets..It works fine...


Thanks in advance for your help..

while(1)
12-20-2002, 02:13 PM
Originally posted by phyte

struct cars van;
van.year=1998;
//gets(van.model);
van.model="TOYOTA";
van.engine_power=500;
van.weight=34.3;

Why can't i initialize the van.model value this way?


van.model is of type char* you can only assign a string to a char pointer on initialization, but the struct was declared and initialized above (struct cars van).

gets() returns a type char* which is a perfect match...

instead do:
strncpy(van.model, "TOYOTA", 15);

wapcaplet
12-20-2002, 02:24 PM
Yep, while(1) is right here. Check out the manpages for strcpy() or strncpy() (if you're assigning a literal string), or sprintf(), if you want to do string formatting before assignment (like if you're assigning from another char * variable).

The reason you got the error you did is that the phrase "TOYOTA" is not a pointer to character (char*), and C doesn't know how to translate it into one. Strings are a pain in C until you get used to them (and even then, they're a pain!)

phyte
12-20-2002, 02:58 PM
Thanks very much for your time guys,

I appreciate it.


Brilliant :).!!

-phyte

Riley
12-20-2002, 07:59 PM
when declaring the car "van" I think it would give you an error if you declare it as struct car van.
It should just be
car van;

while(1)
12-20-2002, 08:13 PM
Originally posted by Riley
when declaring the car "van" I think it would give you an error if you declare it as struct car van.
It should just be
car van;

nope .. in C car is not a type unless you do typedef car_t struct car; in which case car_t will be a type, until then 'struct car' is the type