简体   繁体   English

如何在ANSI C中的结构中使用枚举?

[英]How to use enum within a struct in ANSI C?

Following code has to be used in the main-function, but I don't know how it is used. 以下代码必须在main-function中使用,但我不知道它是如何使用的。

struct SomeItem
{
    enum {MOVIE, MUSIC} itemType;
    union {
        struct Movie* movie;
        struct Music* music;
    };
};

this struct is used in a dynamic linked list with previous/item/next pointer, but I don't know how you can set the enum. 这个结构用在带有previous / item / next指针的动态链表中,但我不知道如何设置枚举。 Or how to initialize it. 或者如何初始化它。

I need to know how it would look like in the main-function. 我需要知道它在main函数中的样子。

biglist.someitem = ???;
/* declaration I use */
struct Library* biglist;

more code to understand what Im trying to do. 更多代码,以了解我想要做什么。

struct Library{
struct SomeItem* someitem;
struct SomeItem* previousItem;
struct SomeItem* nextItem;
};

compiler errors: C2037: left of 'someitem' specifies undefined struct/union 'library' C2065: MOVIE: undeclared identifier 编译错误:C2037:'someitem'左边指定未定义的struct / union'library'C2065:MOVIE:未声明的标识符

Im still a rookie on ANSI C, so dont shoot me ok ;) 我仍然是ANSI C的新秀,所以不要拍我好;)

You're using pointers everywhere, so you need to use -> to reference the items. 你到处都在使用指针,所以你需要使用 - >来引用这些项目。

ie. 即。 biglist->someitem->itemType = MOVIE;

The below code compiles fine with gcc -Wall -strict: 下面的代码用gcc -Wall -strict编译得很好:

struct SomeItem
{
    enum {MOVIE, MUSIC} itemType;
    union {
        struct Movie* movie;
        struct Music* music;
    } item;
};

struct Library{
   struct SomeItem* someitem;
   struct SomeItem* previousItem;
   struct SomeItem* nextItem;
};

int main(void)
{
   struct Library* biglist;

   biglist->someitem->itemType = MOVIE;

   return 0;
}

(Though this code won't run of course, as I'm not allocating any memory for biglist and someitem!) (虽然这个代码当然不会运行,因为我没有为biglist和someitem分配任何内存!)

biglist.someitem.itemType = MOVIE; /* or = MUSIC */

或者,如果someitem是一个指针,

biglist.someitem->itemType = MOVIE; /* or = MUSIC */
struct SomeItem 
{ 
    enum {MOVIE, MUSIC} itemType; 
    union { 
        struct Movie* movie; 
        struct Music* music; 
    } item;
    struct SomeItem *next;
}; 

You may initialize the enum in such a way biglist->someitem = MOVIE; 你可以用biglist-> someitem = MOVIE这样的方式初始化枚举; but the compiler assigns integer values starting from 0. So: biglist->someitem=MOVIE returns 0 or biglist->someitem=MUSIC return 1 但是编译器从0开始分配整数值。所以:biglist-> someitem = MOVIE返回0或biglist-> someitem = MUSIC返回1

check if it helps any good, 检查它是否对任何好处有帮助,

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

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