gpt4 book ai didi

c - 如何在 C 中的多个函数中使用结构体?

转载 作者:行者123 更新时间:2023-11-30 19:12:45 25 4
gpt4 key购买 nike

我希望我的程序要求用户输入汽车的名称、汽车的颜色和汽车的类型。我想使用一个结构体和两个函数来做到这一点。第一个函数接收用户输入的信息,第二个函数仅显示刚刚输入的信息。我尝试对此进行编码,但我不知道如何在两个单独的函数中使用结构。这是我到目前为止所拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Automobiles {
char name_of_car[50];
char color_of_car[50];
char brand_of_car[50];
} auto;

void UserInput() {
printf("What is the name of the car?\n");
scanf(" %s", auto.name_of_car);
printf("What is the color of the car?\n");
scanf(" %s", auto.color_of_car);
printf("What is the brand of the car?\n");
scanf(" %s", auto.brand_of_car);
}

void DisplayOutput() {
printf("%s", auto.name_of_car);
printf("%s", auto.color_of_car);
printf("%s", auto.brand_of_car);
}

int main() {
UserInput();
DisplayOutput();

return 0;
}

最佳答案

如果您想将结构作为参数传递给函数,这里是一个可能的示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Automobile {
char name_of_car[50];
char color_of_car[50];
char brand_of_car[50];
};

void UserInput(struct Automobile *auto) {
printf("What is the name of the car?\n");
scanf(" %s", auto->name_of_car);
printf("What is the color of the car?\n");
scanf(" %s", auto->color_of_car);
printf("What is the brand of the car?\n");
scanf(" %s", auto->brand_of_car);
}

void DisplayOutput(struct Automobile *auto) {
printf("%s", auto->name_of_car);
printf("%s", auto->color_of_car);
printf("%s", auto->brand_of_car);
}

int main() {

// Declare an instance of an Automobile structure.
struct Automobile auto;
// Declare and initialize a pointer to an Automobile structure.
struct Automobile *p_auto = &auto;

// Pass the pointer to the functions.
UserInput(p_auto);
DisplayOutput(p_auto);

return 0;
}

在此示例中,Automobile 结构的实例被分配为 main() 函数的局部变量。然后我们声明一个指针,并初始化它,使其指向该本地实例。然后我们将该指针传递给函数。

您的原始代码将 Automobile 结构的实例声明为全局值,并从您的函数内访问它。一种可能的实现,但并不总是合适的......

如果您想了解更多信息,请阅读本地 C 知识提供商处的“按值传递”和“按引用传递”主题。

关于c - 如何在 C 中的多个函数中使用结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36510336/

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