为结构变量赋值

时间:2015-09-21 14:50:31

标签: c

结构类型定义为:

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

我构造了一个Student类型的变量,我想为它赋值。我怎样才能有效地做到这一点?

int main(){
    Student s1;

    int id = 3;

    char* name = getName(id);

    double score = getScore(id);

    /*Error
    s1 = {id, name, score};
    */

    /*  Can I avoid assigning values individually?
    s1->id = id;
    s1->name = name;
    s1->score= score;
    */

    return 0;
}

3 个答案:

答案 0 :(得分:36)

在C99标准中,您可以使用复合文字指定值:

Student s1;
s1 = (Student){.id = id, .name = name, .score = score};

答案 1 :(得分:13)

注意,结构和指向struct的指针是两个不同的东西。

C为您提供:

  • struct initialization(仅在声明时):

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

    struct Student s1 = {1, "foo", 2.0 }, s2;
    s2 = s1;
    
  • 直接元素访问:

    struct Student s1 ;
    s1.id = 3;
    s1.name = "bar";
    s1.score = 3.0;
    
  • 通过指针进行操作:

    struct Student s1 = {1, "foo", 2.0 }, s2, *ps3;
    ps3 = &s2;
    ps3->id = 3;
    ps3->name = "bar";
    ps3->score = 3.0;
    
  • 初始化函数:

    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);
        ...
    }
    

选择那些(或其他尊重C标准),但s1 = {id, name, score};只是语法错误; - )

答案 2 :(得分:3)

  

我可以避免单独分配值吗?

如果值已经是类似struct的一部分,您可以执行此操作:

Student s1 = {.id = id, .name = name, .score = score};

创建Student的实例并初始化您指定的字段。这可能不比单独分配值更有效,但它确实使代码简洁。一旦你有一个现有的Student实例,就可以通过简单的赋值来复制它:

Student s2;
s2 = s1;    // copies the contents of s1 into s2

如果值都在单独的变量中,并且您没有初始化Student,那么您可能需要单独分配值。但是,您总是可以编写一个为您执行此操作的函数,以便您具有以下内容:

setupStudent(s3, id, name, score);

这样可以保持代码简短,确保每次都以相同的方式填充结构,并在({not})Student的定义发生变化时简化生活。

相关问题