为结构指针赋值的语法 [英] Syntax to assign values to struct pointer

查看:31
本文介绍了为结构指针赋值的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于语法和代码的快速问题.

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

我刚刚找到了一种在 C 中声明结构体的方法,这与我目前所见略有不同.

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

这是示例代码:

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

将变量分配为 .var_name 工作正常,您可以按您喜欢的任何顺序分配它.我喜欢这种方法,所以我开始尝试并因此碰壁.如果我要声明:

Assigning variables as .var_name works fine and you can assign it in any order you'd like. 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?

谢谢!

推荐答案

一般来说,你不能给指针赋值".一个指针只存储一个值,它是一个已经存在的对象的地址.

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

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

但是您可以使用涉及复合文字的技巧(自 C99 起可用):

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

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

这里我们使用复合字面量来创建一个新的未命名结构对象,然后我们将其内容复制到 *p 中.

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

同样的特性可以用来去掉第一个例子中的s:

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

但是在这个版本中 p 仍然指向自动内存(就像一个局部变量).

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

这篇关于为结构指针赋值的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆