c - 如何使用函数将字符串添加到结构中?

标签 c string struct char void

我制作了一个 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);
}

最佳答案

您的代码中有很多错误!首先解决“其他”问题:

  1. 在使用 AddCarShowCar 之前,您需要提供它们的函数原型(prototype),否则编译器将假定它们返回 int 然后在看到实际定义时提示。
  2. 您的 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/

相关文章:

c - 通过指针访问结构

c++ - 未定义的行为是否适用于 asm 代码?

android:AutoCompleteTextView 的字符串数组大小限制

c - 为什么灵活数组成员的静态初始化有效?

c - 带有使用关键字 "extern"的结构体和函数原型(prototype)的头文件

c - MPLAB IDE v2.05

c - 在 C 语言中扩展 Ruby - 将参数转换为 C 类型

python - 如何从 python 中的字符串中删除 ANSI 转义序列

C++模板方法

c - 存储在结构中的字符串打印不正确