gpt4 book ai didi

c - C中的字符串问题

转载 作者:太空狗 更新时间:2023-10-29 14:55:28 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com