Syntax to assign values to struct pointer

后端 未结 1 1763
不知归路
不知归路 2021-01-26 05:14

I have a quick question about the syntax and the code.

I just found out a way to declare the struct in C which is a bit different from what I\'ve seen so far.

Th

相关标签:
1条回答
  • 2021-01-26 05:50

    Generally speaking, you can't "assign values to a pointer". A pointer only stores a single value, which is the address of an already existing object.

    If you have a pointer pointing to an existing struct variable, you can just initialize that:

    struct student s = { .name = "Max", .age = 15, .grade = 8 };
    struct student *p = &s;
    

    If you want to use dynamic memory allocation, things get a bit tricker:

    struct student *p = malloc(sizeof *p);
    if (!p) {
        ...
    }
    

    malloc gives you uninitialized memory, and you cannot use initializer syntax with existing objects.

    But you can use a trick involving compound literals (available since C99):

    *p = (struct student){ .name = "Max", .age = 15, .grade = 8 };
    

    Here we use a compound literal to create a new unnamed struct object whose contents we then copy into *p.

    The same feature can be used to get rid of s in the first example:

    struct student *p = &(struct student){ .name = "Max", .age = 15, .grade = 8 };
    

    But in this version p still points to automatic memory (like a local variable).

    0 讨论(0)
提交回复
热议问题