c - 为什么我们不能将结构对象作为结构内部的数据成员?

标签 c

以下代码生成编译错误。 我不明白为什么这不起作用,谁能解释为什么会这样。

struct abc {
    int a;
    int b;
    struct abc var;
} a1;

int main()
{
    printf("%d",a1.a);
    return 0;
}

以上代码无效并返回错误:error: field 'var' has incomplete type.

struct abc
{
    int a;
    int b;
    struct abc *var;
} a1;

int main()
{

    printf("%d",a1.a);
    return 0;
}

最佳答案

结构类型在用终止 完成定义之前是不完整的。您的第一个示例将具有嵌套结构的无限递归,这可能不是您想要的。第二个示例仅包含一个指向该结构的指针,这很好。

来自规范,6.7.2.1 结构和 union 说明符,第 3 段:

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself),

关于c - 为什么我们不能将结构对象作为结构内部的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19419294/

相关文章:

c - fcntl如何知道哪个进程持有锁文件?

c - 为什么 snprintf 更改输出字符串?

c - 如何在 C 中将字符串小写?

c - 为什么 gcc -Wformat 不对 unsigned int 上的 printf %d 发出警告?

c++ - 超越结构的一个元素以查看另一个元素是否合法?

c - C语言验证密码

c - 字符 * 和字符 [ ] 的 scanf 之间的区别?

c - fscanf : how to read but not assign commas?

c - 基于管道的进程间通信程序

c - 按特定字段对二维字符串数组进行排序