Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with strings in C

Tags:

c

string

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 ?

like image 534
jingo Avatar asked Sep 27 '11 10:09

jingo


People also ask

What is the problem with C string?

Disadvantages of C-stringsWorking with C-strings is not intuitive. Functions are required to compare strings, and the output of the strcmp functions is not intuitive either. For functions like strcpy and strcat , the programmer is required to remember the correct argument order for each call.

Why are strings so complicated in C?

For C: because strings are almost always variable-length and so you have to deal with heap allocation and manual memory management.

Can you use strings in C?

C does not have a built-in string function. To work with strings, you have to use character arrays.

Is %s string in C?

Note: The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to print and read strings directly.


1 Answers

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:

  • Assign to array
  • How can an array be an lvalue, if you can't assign to it?
like image 151
cnicutar Avatar answered Oct 28 '22 13:10

cnicutar