我为什么可以使用一个不存在的类型的typedef? [英] Why can I use a typedef of a type that doesn't exist?

查看:131
本文介绍了我为什么可以使用一个不存在的类型的typedef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的小程序在编译gcc和运行的罚款:

The following small program compiles on gcc and runs fine:

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

typedef struct foo dne;

int main(int argc, char *argv[]) {
    dne *dne_var = malloc(sizeof(void*));
    printf("%p\n", dne_var);
    return 0;
}

为什么是有效的typedef?

Why is the typedef valid?

推荐答案

typedef struct foo dne;

隐式声明的(不完全在这一点)结构结构美孚。一个指向不完全类型是一个完整的类型,所以如它的大小是已知的,你可以声明该类型的对象。但是,直到你提供的是一个完整的声明,所以例如结构美孚本身是不完整的。

implicitly declares an (incomplete at this point) structure struct foo. A pointer to an incomplete type is a complete type, so e.g. it’s size is known and you can declare an object of that type. However, struct foo itself isn’t complete until you provide a full declaration of it, so e.g.

dne dne_var;

或解引用指针以访问结构的字段将是无效的。

or dereferencing your pointer to access the fields of the structure would be invalid.

这篇关于我为什么可以使用一个不存在的类型的typedef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆