c - C中的字符串问题

标签 c string

我是 C 世界的新手,我有两个可能很愚蠢的问题。

我正在阅读有关 C 中的结构的信息,这就是我卡住的地方。假设我们有这样的结构

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"

在这种情况下如何将文本传递到 Ford.model 中?

我的第二个问题也是关于字符串的。 此代码工作正常

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

但是这个没有

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

谁能解释为什么它不起作用?

最佳答案

这不是你在 C 中复制字符串的方式。试试

strcpy(Ford.model, "Focus");

或者(但使用 very different semantics ):

typedef structs {
  char const *model;
  int yearOfManufacture;
  int price;
} Car;

model = "Focus";

这些 C 常见问题解答更多地解释了这个问题:

关于c - C中的字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7567541/

相关文章:

c - Linux,kprobes/kretprobes : a way to recover [from registers?] 探测函数的参数?

c - 多次输入变量answer会退出整个程序

c - C中的浮点常量,位表示

javascript - 有没有办法从单个字符中获取 charCode?

string - 匹配到 "::"之前的模式不适用于 string.gsub

c - 在 linux 中通过 C 访问 excel 表

c - 什么时候使用 strdup 是个好主意(相对于 malloc/strcpy)

python - 在python中大约将unicode字符串转换为ascii字符串

c++ - 如何将 LPWSTR 转换为 GUID?

c++ - accessing是在使用CTRP时访问父构造函数UB中的子属性吗?