代码之家  ›  专栏  ›  技术社区  ›  Luka Rahne

结构的typedef

  •  1
  • Luka Rahne  · 技术社区  · 14 年前

    我在项目中使用结构的方式如下:

    typedef struct
    {
        int str1_val1;
        int str1_val2;
    } struct1;
    

    typedef struct
    {
        int str2_val1;
        int str2_val2;
        struct1* str2_val3;
    } struct2;
    

    有没有可能我以某种方式破解了这个定义,我只在代码中使用类型,比如

    struct2* a;
    a = (struct2*) malloc(sizeof(struct2));
    

    不使用关键字 struct ?

    4 回复  |  直到 14 年前
        1
  •  2
  •   slashmais    14 年前

    是,如下:

    struct _struct1
    {
    ...
    };
    typedef struct _struct1 struct1;
    
    struct _struct2
    {
    ...
    };
    typedef struct _struct2 struct2;
    
    ...
    
    struct2 *a;
    a = (struct2*)malloc(sizeof(struct2));
    
        2
  •  0
  •   sizzzzlerz    14 年前

    是的,您可以使用typedef'ed符号而不需要struct关键字。编译器只是使用这个名称作为您前面定义的结构的别名。

    在您的示例中,malloc返回一个指向内存的指针。因此,你的陈述应该是

    a = (struct2 *)malloc(sizeof(struct2));
    
        3
  •  0
  •   salezica    14 年前

    只是分享一下,我见过这种方法,虽然我个人不喜欢它(我喜欢所有命名和标记为p的东西,我不喜欢在malloc中使用变量名),但有人可能会喜欢。

    typedef struct {
        ...
    } *some_t;
    
    int main() {
        some_t var = (some_t) malloc(sizeof(*var));
    }
    
        4
  •  0
  •   pm100    14 年前

    作为脚注。如果你在C++中编码,那么你就不需要做TyPulf了,Stutt是一个自动的类型。