我是 C 的新手,我想知道如何访问放置在结构内的结构内的元素。

struct profile_t
{
    unsigned char length;
    unsigned char type;
    unsigned char *data;
};

typedef struct profile_datagram_t
{
    unsigned char src[4];
    unsigned char dst[4];
    unsigned char ver;
    unsigned char n;
    struct profile_t profiles[MAXPROFILES];
} header;

如何访问 profile_t 中的元素?

最佳答案

struct profile_t;

上面的语句不会创建 profile_t 类型的对象。你需要做的是——
struct profile_t inObj ;

然后为 profile_datagram_t 创建对象。 IE。,
header outObj ;  // header typedef for profile_datagram_t

现在您可以访问元素,例如 -
outObj.inObj.type = 'a' ; // As an example

在 C++ 中,当为结构创建对象时, struct 关键字不是必需的。

关于您的问题编辑和评论:
struct profile_t profiles[MAXPROFILES];
profilesprofile_t 类型的对象数组。要访问单个对象,只需使用 [] 运算符。 IE。,
header obj ;
obj.profiles[0].type = 'a' ; // Example
obj.profiles[i] ,其中 i 可以采用从 0 MAXPROFILES - 1 的值,给出索引 i 处的对象。

关于c - 在 C 和 C++ 中使用结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6839052/

10-13 07:34
查看更多