The problem with strings in C

I'm new to C world, and I have two probably stupid questions.

I read about structures in C, and this is where I am stuck. Let them say that we have a 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 transfer text to Ford.model in this case?

My second question also concerns strings. This code works great

char model[50] = "Focus";
printf("Model is %s", model);

But it is not

char model[50];
model = "Focus";

Can anyone explain why it is not working?

+5
source share
5 answers

This is not how you copy lines 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 frequently asked questions explain more about the problem:

+5
source

" ":

  • ,
  • ,

, .

, .

char

char arr[] = "foobar";
char arr[] = {'f', 'o', 'o', 'b', 'a', 'r', '\0'};
int arr[] = {1, 2, 3, 4};
// ...

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;

"" char - strcpy() <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;
}
+4

(Ford.model = "Focus") . , strcpy:

strcpy(Ford.model, "Focus");

stdlib , , strncpy:

strncpy(Ford.model, "Focus", sizeof Ford.model);

, , , ... .

+1

You cannot assign an array of characters with =, you can only initialize it.

When you write

char model[50] = "Focus";

this is initialization.

When you write

model = ...

that is, the destination. And, as I said, the assignment of character arrays is not allowed.

You need to copy an array of characters using strcpy(), for example. strcpy(model, "Focus").

0
source

You can assign a string during the definition, but in another place you must use a different method, for example, a function strcpy():

char model[50];
strcpy(model, "Focus");
0
source

All Articles