简体   繁体   English

为结构指针赋值的语法

[英]Syntax to assign values to struct pointer

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. 我刚刚发现了一种在C中声明结构的方法,这与我到目前为止看到的有点不同。

This is the sample code: 这是示例代码:

#include <stdio.h>
struct student {
    int age;
    int grade;
    char* name;
};
int main () {
    struct student s = { .name = "Max", .age = 15, .grade = 8 };
    return 0;
}

Assigning variables as .var_name works fine and you can assign it in any order you'd like. 将变量指定为.var_name可以正常工作,您可以按照您想要的任何顺序进行分配。 I liked this approach so I started experimenting and thus hit the wall. 我喜欢这种方法,所以我开始尝试,因此撞墙。 If I were to declare: 如果我要宣布:

struct student *s = { ->name = "Max", ->age = 15, ->grade = 8 };

This won't work. 这不行。 Is there any syntax that could give the same results when using a pointer as the code above? 当使用指针作为上面的代码时,是否有任何语法可以提供相同的结果?

Thanks! 谢谢!

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变量,则可以初始化:

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. malloc为您提供未初始化的内存,并且您不能对现有对象使用初始化程序语法。

But you can use a trick involving compound literals (available since C99): 但你可以使用涉及复合文字的技巧(自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 . 这里我们使用复合文字来创建一个新的未命名的struct对象,然后将其内容复制到*p

The same feature can be used to get rid of s in the first example: 在第一个示例中,可以使用相同的功能来摆脱s

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). 但在这个版本中, p仍指向自动内存(如局部变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM