【问题标题】:Error: Conversion to non-scalar type requested错误:请求转换为非标量类型
【发布时间】:2012-03-05 03:34:27
【问题描述】:

我在尝试 malloc 这个结构时遇到了一个小问题。 这是结构的代码:

typedef struct stats {                  
    int strength;               
    int wisdom;                 
    int agility;                
} stats;

typedef struct inventory {
    int n_items;
    char **wepons;
    char **armor;
    char **potions;
    char **special;
} inventory;

typedef struct rooms {
    int n_monsters;
    int visited;
    struct rooms *nentry;
    struct rooms *sentry;
    struct rooms *wentry;
    struct rooms *eentry;
    struct monster *monsters;
} rooms;

typedef struct monster {
    int difficulty;
    char *name;
    char *type;
    int hp;
} monster;

typedef struct dungeon {
    char *name;
    int n_rooms;
    rooms *rm;
} dungeon;

typedef struct player {
    int maxhealth;
    int curhealth;
    int mana;
    char *class;
    char *condition;
    stats stats;
    rooms c_room;
} player;

typedef struct game_structure {
    player p1;
    dungeon d;
} game_structure;

这是我遇到问题的代码:

dungeon d1 = (dungeon) malloc(sizeof(dungeon));

它给了我错误“错误:请求转换为非标量类型” 有人可以帮我理解这是为什么吗?

【问题讨论】:

    标签: c struct malloc


    【解决方案1】:

    您不能将任何内容转换为结构类型。我猜你的意思是:

    dungeon *d1 = (dungeon *)malloc(sizeof(dungeon));
    

    但请不要将malloc() 的返回值强制转换为C 程序。

    dungeon *d1 = malloc(sizeof(dungeon));
    

    可以正常工作,不会向您隐藏 #include 错误。

    【讨论】:

    • 如果将malloc()的返回值强制转换会有什么问题?
    • @PriteshAcharya,对于现代编译器来说可能不多。也就是说,它是非惯用语。阅读this question and its answers 进行大量详细讨论。
    • struct student_simple { int rollno; char *name; }; struct student_simple *s2 = malloc(sizeof(struct student_simple *)); struct student_simple *s3 = malloc(sizeof(struct student_simple )); 之间有什么区别我可以毫无问题地使用 s2 和 s3 但是当我检查 gdb gdb$ p sizeof(struct student_simple) 中的大小时给出 16 gdb$ @987654329 @ 给出 8 一个 8 字节的 malloc 是如何存储 student_simple 结构的。?
    • 未定义的行为是未定义的。任何事情都可能发生,包括正确行为的出现。使用s3 表格,它是正确的。不过,您可能应该将问题作为问题发布,而不是作为无关问题的 cmets。
    • @PriteshAcharya 您应该分配结构内数据所需的实际大小,而不是指针的大小(因此没有星号)。指针只是一个内存地址,它通常占用几个字节(毕竟它只是一个数字)。结构内的数据没有虚拟限制,重要的可以是 TB。如果您的结构像这种情况一样非常小,您可能不会注意到差异,因为您分配的字节数已经足够了。尝试使用更大的结构,您会发现问题。
    【解决方案2】:

    malloc 返回一个指针,所以您可能想要的是以下内容:

    dungeon* d1 = malloc(sizeof(dungeon));
    

    这是 malloc 的样子:

    void *malloc( size_t size );
    

    你可以看到它返回void*,但是你shouldn't cast the return value

    【讨论】:

      【解决方案3】:

      malloc分配的内存必须存储在指向对象的指针中,而不是对象本身中:

      dungeon *d1 = malloc(sizeof(dungeon));
      

      【讨论】:

        猜你喜欢
        • 2019-01-22
        • 2015-12-01
        • 2013-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多