构造和初始化数组

时间:2017-08-07 23:58:44

标签: c arrays struct

我一直在尝试研究如何对数组使用结构,并且不了解如何初始化数组的前三项,如代码中所示。我在尝试打印或扫描数组的值时也遇到错误,因为它说它们都是整数,即使我已经将它们声明为字符串/字符。任何帮助都会很棒,谢谢。

#include <stdlib.h>
#include <stdio.h>
#define MAXLEN 100

typedef struct{
  char name;          <<have now changed all to [MAXLEN+1]
  char surname;       <<
  char UUN;           <<
  char department;    <<  
  char gender;
  int age;
} student_t;


int main(void){
  student_t details[5];
  int i, n;

  details[0].name = "John";           <<should all the '=' be ',' instead?
  details[0].surname = "Bishop";      <<do not understand how to initialize
  details[0].UUN = "s1234";
  details[0].department = "Inf";
  details[0].gender = 'm';
  details[0].age = 18;

  details[1].name = "Lady";
  details[1].surname = "Cook";
  details[1].UUN = "s2345";
  details[1].department = "Eng";
  details[1].gender = 'f';
  details[1].age = 21;

  details[2].name = "James";
  details[2].surname = "Jackson";
  details[2].UUN = "s3456";
  details[2].department = "Eng";
  details[2].gender = 'm';
  details[2].age = 17;

  for(i = 3; i < 6; i++){
    printf("Enter first name second name UUN department gender age: \n");
    scanf(" %s %s %s %s %c %d", details[i].name, details[i].surname, details[i].UUN, details[i].department, details[i].gender, details[i].age);
  }

  for(n = 0; n < 6;n++){
    printf("details: %s", details[n].name);
  }

  return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:0)

你必须把每个字符串放大。

char name;应为char name[30]; //for example

你应该使用strcpy(来自string.h)将char数组(字符串)放在变量上。

details[0].name = "John"; should be  strcpy(details[0].name,"John");