【问题标题】:Passing struct array to function for input将结构数组传递给函数以进行输入
【发布时间】:2018-07-29 04:02:26
【问题描述】:

我正在开发一个 C 语言程序,该程序收集员工的数据,例如姓名、费率和工时。问题是我需要使用struct

我正在尝试将结构数组传递给load() 函数,用户将在其中输入员工的姓名、小时数和费率,但似乎我做错了。你能告诉我有什么问题吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 3
int i = 0;
struct Employee
{
    char name[20];
    float rate;
    float hours;

}employee;


void load(struct Employee *guys);
void printout();
void edit();
void realedit();
void print();

int main(void)
{   
    int x=0;
    struct Employee guys[size];


    while (x != 5)
    {
        printf("Main Menu\n");
        printf("1. Add Employee\n");
        printf("2. Edit Employee\n");
        printf("3. Print Employee\n");
        Printf("4. Print All Employees\n");
        printf("5. Quit");
        scanf_s("%d", &x);

        switch (x) 
        {
        case 1: load(guys[i]);
            break;


        default: printf("Please enter valid option.\n\n");
            break;
        }
    }


    system("pause");
    return 0;

}

void load(struct Employee *guys)
{
    puts("\ntype name:\n");
    scanf_s("%s", &guys[i]->name, 20);

    puts("\ntype hourly rate:\n");
    scanf_s("%f", &guys[i]->rate);

    puts("\ntype hours worked:\n");
    scanf_s("%f", &guys[i]->hours);


    i++;
}

【问题讨论】:

  • 当您将 guy[i] 传递给 load 时,让 load retreive Employee &emp。然后只需使用 emp.name 存储数据。请注意,将“i”作为全局变量并不是一个好习惯。
  • 这里 load(guys[i]); 按值传递结构,但 load() 参数需要一个指向 struct Employee 的指针。
  • 别忘了检查scanf_s()调用是否成功; main()中的那个要检查确保返回1,否则有问题。
  • int i = 0; 的一个全局变量只是自找麻烦。

标签: c arrays pointers struct


【解决方案1】:

随着

load(guys[i]);

在您的程序中,您将guys 数组的ith 元素按值传递给load()。所以load() 中使用的实际上是一个副本更改,不会影响main() 中的原始值。

相反,您可以将指向 ith 元素的指针传递给 load() 之类的

load(&guys[i]);

并使用-&gt; 运算符访问struct 中的变量。

void load(struct Employee *guys)
{
    puts("\ntype name:\n");
    scanf_s("%s", guys->name, 20);

    puts("\ntype hourly rate:\n");
    scanf_s("%f", guys->rate);

    puts("\ntype hours worked:\n");
    scanf_s("%f", guys->hours);
}

并且无需使用[i] 进行索引,因为我们会一一处理元素。


scanf_s("%s", &guys[i]->name, 20);

函数需要数组的基地址。所以使用

scanf_s("%s", guys[i]->name, 20);

因为数组的名称衰减为指向数组第一个元素的指针。

至于你在中使用system()

system("pause");

考虑阅读 Why should the system() function be avoided in C and C++?

另外,请注意puts() 将在末尾自动打印\n。因此,如果您认为合适,可以取消 \n

你有一个小错字。

Printf("4. Print All Employees\n");

应该是

printf("4. Print All Employees\n");

【讨论】:

  • 或者:load(guys + i);
  • @Aconcagua 是的,是的。
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 2015-02-24
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多