Assign values to structure variables

后端 未结 3 417
感动是毒
感动是毒 2021-01-30 18:31

A structure type is defined as:

typedef struct student{
    int id;
    char* name;
    double score;
} Student;

I construct a variable of type

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 19:11

    Beware, struct and pointer to struct are 2 different things.

    C offers you:

    • struct initialization (only at declaration time):

      struct Student s1 = {1, "foo", 2.0 }, s2;
      
    • struct copy:

      struct Student s1 = {1, "foo", 2.0 }, s2;
      s2 = s1;
      
    • direct element access:

      struct Student s1 ;
      s1.id = 3;
      s1.name = "bar";
      s1.score = 3.0;
      
    • manipulation through pointer:

      struct Student s1 = {1, "foo", 2.0 }, s2, *ps3;
      ps3 = &s2;
      ps3->id = 3;
      ps3->name = "bar";
      ps3->score = 3.0;
      
    • initialization function:

      void initStudent(struct Student *st, int id, char *name, double score) {
          st->id = id;
          st->name = name;
          st->score = score;
      }
      ...
      int main() {
          ...
          struct Student s1;
          iniStudent(&s1, 1, "foo", 2.0);
          ...
      }
      

    Pick among those (or other respecting C standard), but s1 = {id, name, score}; is nothing but a syntax error ;-)

提交回复
热议问题