我制作了一个 parking 系统,使用 void 函数输入车辆信息。 但我不知道如何使用 void 将字符串放入结构中。
这是我的代码。 我的错误在哪里?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct car {
char plate[10];
char model[20];
char color[10];
};
void main() {
struct car c[4];
AddCar(c[0], "43ds43", "ford", "blue");
ShowCar(c[0]);
return 0;
}
// I guess my mistake is here
void AddCar(struct car c, char p[10], char m[10], char r[10]) {
strcpy(c.plate, p);
strcpy(c.model, m);
strcpy(c.color, r);
}
void ShowCar(struct car c) {
printf("Plate: %s Model: %s Color: %s\n-------", c.plate, c.model, c.color);
}
最佳答案
您的代码中有很多错误!首先解决“其他”问题:
- 在使用
AddCar
和ShowCar
之前,您需要提供它们的函数原型(prototype),否则编译器将假定它们返回int
然后在看到实际定义时提示。 - 您的
main
函数(正确地)返回0
但它被声明为void
- 因此将其更改为int main(. ..)
.
“真正”的问题是:您将 car
结构传递给 AddCar
按值 - 这意味着已制作副本,然后传递给函数。对该副本的更改不会影响调用模块中的变量(即main
中)。要解决此问题,您需要将指针传递给car
结构,并使用->
运算符(代替 .
运算符)在该函数中。
这是代码的“固定”版本,在我进行重大更改的地方添加了注释:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct car {
char plate[10];
char model[20];
char color[10];
};
// Add your functions' prototypes before you use them...
void AddCar(struct car *c, char p[10], char m[10], char r[10]);
void ShowCar(struct car c);
int main() // If you return an int, you must declare that you do!
{
struct car c[4];
// Here, we pass a pointer to `c[0]` by adding the `&` (address of)...
AddCar(&c[0], "43ds43", "ford", "blue");
ShowCar(c[0]);
return 0;
}
void AddCar(struct car *c, char p[10], char m[10], char r[10])
{ // ^ To modify a variable, the function needs a POINTER to it!
strcpy(c->plate, p);
strcpy(c->model, m); // For pointers to structures, we can use "->" in place of "."
strcpy(c->color, r);
}
void ShowCar(struct car c)
{
printf("Plate: %s Model: %s Color: %s\n-------", c.plate, c.model, c.color);
}
请随时要求进一步澄清和/或解释。
关于c - 如何使用函数将字符串添加到结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61195643/