how would i be able to initialize that var to mustang for ex.?Code:struct car { char name[40]; }car1;
how would i be able to initialize that var to mustang for ex.?Code:struct car { char name[40]; }car1;
strncpy( car1.name, "Mustang", 39);
car1.name[30]=NULL;
There are many ways to do it. That is a pretty good one.
Quzah.
Hope is the first step on the road to disappointment.
You can only do string assignments that way during creation of the variable.Originally posted by MethodMan
how come i cant do
car.name = "Mustang";
struct car car1 = { "Mustang" };
The other reason you can't is that this is C. In C, you cannot just assign strings values to arrays like that. In C++ it's possible to override the assignment operator, and you could then do that, but not in C. Strings are not handled the same as integers or what not. The reason they aren't is that there is no "string" type in C. "Strings" are just arrays of characters.
Quzah.
Hope is the first step on the road to disappointment.
For the same reason you can't do
char name[40] = "firstline";
name = "anotherline";
You could do
car1.name[22] = 'A';
Right, because here you're assigning a single character, not an array of characters in one shot. (For the original poster's sake.)Originally posted by Barjor
You could do
car1.name[22] = 'A';
Quzah.
Hope is the first step on the road to disappointment.
do you mean you want to assign it on creation or create a variable of that data type and then assign it, if so you would do something like:
not 100% which way ya meant, if its assign it as a constant for all the ones you create then the previous posts are the way to go.Code:struct car { char name[40]; }car1; int main() { car1 tempcar; strcpy(tempcar.name,"Mustang"); }
Your code won't compile for two reasons:Originally posted by Bull
do you mean you want to assign it on creation or create a variable of that data type and then assign it, if so you would do something like:
not 100% which way ya meant, if its assign it as a constant for all the ones you create then the previous posts are the way to go.Code:struct car { char name[40]; }car1; int main() { car1 tempcar; strcpy(tempcar.name,"Mustang"); }
a) 'car1 tempcar' is not valid. 'car1' is an instance of 'struct car'. It is global so you do not need 'tempcar'.
b) 'car1' is not a typedef, nor is it the name of the structure.
I prefer strncpy, as shown above. Otherwise...
strcpy( car1.name, "this really long car name just killed your application" );
Quzah.
Hope is the first step on the road to disappointment.