如何创建结构的新实例 [英] How to create a new instance of a struct

查看:44
本文介绍了如何创建结构的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建结构的新实例的正确方法是什么?给出结构:

What is the correct way to create a new instance of a struct? Given the struct:

struct listitem {
    int val;
    char * def;
    struct listitem * next;
};

我看过两种方法.

第一种方法(xCode表示这是在重新定义结构,而且是错误的):

The first way (xCode says this is redefining the struct and wrong):

struct listitem* newItem = malloc(sizeof(struct listitem));

第二种方式:

listitem* newItem = malloc(sizeof(listitem));

或者,还有另一种方法吗?

Alternatively, is there another way?

推荐答案

第二种方法仅在您使用过的情况下有效

The second way only works if you used

typedef struct listitem listitem;

在声明任何类型为 listitem 的变量之前.您还可以仅静态分配结构,而不是动态分配它:

before any declaration of a variable with type listitem. You can also just statically allocate the structure rather than dynamically allocating it:

struct listitem newItem;

您演示的方式就像对要创建的每个 int 执行以下操作:

The way you've demonstrated is like doing the following for every int you want to create:

int *myInt = malloc(sizeof(int));

这篇关于如何创建结构的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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