Reputation: 1074
I'm newbie in C world and I have two probably stupid questions.
I'm reading about structures in C and here is where I stuck. Let say we have structure like this
typedef structs {
char model[50];
int yearOfManufacture;
int price;
} Car;
Car Ford;
Ford.yearOfManufacture = 1997;
Ford.price = 3000;
//The line below gives me an error "Array type char[50] is not assignable
Ford.model = "Focus"
How to pass text into Ford.model in that case ?
My second question is also about strings. This code works fine
char model[50] = "Focus";
printf("Model is %s", model);
But this one doesn't
char model[50];
model = "Focus";
Can anyone explain why it doesn't work ?
Upvotes: 5
Views: 3293
Reputation: 3760
You can assign a string during definition, but anywhere else you have to use a different method, like the strcpy()
function:
char model[50];
strcpy(model, "Focus");
Upvotes: 0
Reputation: 35039
This (Ford.model = "Focus"
) is not possible. You have to copy the string into the array in the struct, best with strcpy
:
strcpy(Ford.model, "Focus");
If your stdlib supports it, you should also consider an overflow safe version, e.g strncpy
:
strncpy(Ford.model, "Focus", sizeof Ford.model);
At least I think its an extension function and not in the standard... I'm not sure.
Upvotes: 1
Reputation: 108968
There are two ways to "put values in objects":
Though the syntax is similar, they represent different concepts.
You can initialize an array, but you cannot assign to it.
Also there's a special construct to initialize char
arrays based on string literals
char arr[] = "foobar";
char arr[] = {'f', 'o', 'o', 'b', 'a', 'r', '\0'};
int arr[] = {1, 2, 3, 4};
// ...
but, assignement must be done element by element
char arr[4];
arr[0] = arr[1] = arr[2] = 'X';
arr[3] = '\0';
int arr[4];
arr[0] = arr[1] = arr[2] = 42;
arr[3] = -1;
A "special" way to assign elements of a char
arrays one-by-one with a single statement is to use the library function strcpy()
with prototype in <string.h>
#include <string.h>
int main(void) {
char arr[10];
strcpy(arr, "foo"); // same as arr[0]='f'; arr[1]=arr[2]='o'; arr[3]='\0';
return 0;
}
Upvotes: 4
Reputation: 182609
That's not how you copy strings in C. Try
strcpy(Ford.model, "Focus");
Alternatively (but with very different semantics):
typedef structs {
char const *model;
int yearOfManufacture;
int price;
} Car;
model = "Focus";
These C FAQs explain more about the issue:
Upvotes: 5
Reputation: 612794
You can't assign to a character array with =
, you can only initialize it.
When you write
char model[50] = "Focus";
that is a initialization.
When you write
model = ...
that is an assignment. And, as I said, assignment to character arrays is not allowed.
You need to copy to the character array using strcpy()
, e.g. strcpy(model, "Focus")
.
Upvotes: 0