如何初始化struct并从函数调用main中显示

时间:2017-04-26 12:05:24

标签: c data-structures

我想创建一个结构并在InitiateA中初始化它们并在DisplayA中打印并在Main中调用它们。我试着这样做,但似乎什么都没有用?

#include <string.h>

struct Penalty{
  // Provide structure definition for Penalty here
  double fine;
  char Identity[20];
  int i;
};

void InitiateA (struct Penalty data[]);
void DisplayA (struct Penalty data[]);

int main(){

  struct Penalty rule[3];
  struct i;

  DisplayA(rule);

  rule[0].fine = 20.00;
  strcpy(rule[0].Identity, "Student" );

  rule[1].fine = 30.00;
  strcpy(rule[1].Identity , "Staff");

  rule[2].fine = 50.00;
  strcpy(rule[2].Identity , "Vendor");

  for(i=0;i<3;i++) {
    printf("%d%s",rule[i].fine,rule[i].Identity);
  }   

  return 0;
}

我不确定如何将此功能调用到主功能

void InitiateA (struct Penalty data[]){
  //intialize data here.
  printf("identity\n");
  printf("%d",rule[i].Identity);
  return;
}

void DisplayA (struct Penalty data[]){
  //display data here
  printf("Fine : RM %d\n", data[i].fine);
  return;
}

我做错了吗?

2 个答案:

答案 0 :(得分:0)

这是InitiateA()中的错误:

printf("%d",rule[i].Identity);

你的意思是

printf("%d", data[i].Identity);

您无法引用变量rule,此时它不在范围内(它是main()中的本地变量。)

你需要从main()

这样调用它
InitiateA(rule);

答案 1 :(得分:0)

我设法完成了它们!

#include <string.h>
#include <stdio.h>
struct Penalty{

double fine;
char Identity[20];
};

void InitiateA (struct Penalty data[]);
void DisplayA (struct Penalty data[]);


int main(){

struct Penalty rule[3];

InitiateA(rule);
DisplayA(rule);

system ("pause");

}

void InitiateA (struct Penalty data[]){
  data[0].fine = 20.00;
strcpy(data[0].Identity, "Student" );

data[1].fine = 30.00;
 strcpy(data[1].Identity , "Staff");

 data[2].fine = 50.00;
strcpy(data[2].Identity , "Vendor");

}

 void DisplayA (struct Penalty data[]){
  int i;
 for(i=0;i<3;i++){
 printf("%s %.2f \n",data[i].Identity, data[i].fine);
}
}