C-实际声明时未声明(此函数中的第一次使用)

时间:2019-11-27 23:52:04

标签: c

我简化了代码,但仍然不明白为什么在上面声明结构时未声明结构

    #include <stdlib.h>
    #include <stdio.h>

    int main()
    {
        struct s
        {
            char n[20];
            char p[20];
        };

        struct s X = malloc(sizeof(s));

        return 0;
    }

2 个答案:

答案 0 :(得分:3)

使用类似typedef的

    typedef struct s
    {
        char n[20];
        char p[20];
    } s;

然后

struct s *X = malloc(sizeof(s));

s *X = malloc(sizeof(s));

甚至喜欢

s *X = malloc(sizeof( *X));

或者没有typedef,您必须使用关键字struct

struct s *X = malloc(sizeof(struct s));

struct s *X = malloc(sizeof( *X));

答案 1 :(得分:2)

问题是您正在定义类型struct s,但未声明名为s的变量或类型。

由于这个原因,当您调用sizeof(s)时,未声明符号s

作为旁注,变量X被定义为struct s变量。如果要使用malloc,则可能需要将内存分配给指针(struct s *X = ...)。

考虑:

#include <stdlib.h>
#include <stdio.h>

int main()
{
    struct s
    {
        char n[20];
        char p[20];
    };

    struct s *X = malloc(sizeof(struct s)); /* <= note the struct keyword and pointer */

    return 0;
}

此外,如果您不想引用该类型名称,则无需命名struct类型。使用匿名结构是完全合法的:

#include <stdlib.h>
#include <stdio.h>

int main()
{
    struct
    {
        char n[20];
        char p[20];
    } * x; /* <= note the variable name */

    x = malloc(sizeof(*x));

    return 0;
}