【问题标题】:Can't print structure variable无法打印结构变量
【发布时间】:2013-03-07 23:20:03
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char name[20];
    int age;
} employee;

int main(int argc, char** argv)
{
    struct employee em1 = {"Jack", 19};
    printf("%s", em1.name);
    return 0;
}

这似乎不起作用,因为正如编译器所说,该变量的“struct employee”类型不完整。怎么了?

【问题讨论】:

    标签: c struct printf


    【解决方案1】:

    中删除结构
     struct employee em1 = {"Jack", 19};
    

    你用过

    typedef struct
    {
    char name[20];
    int age;
    }
    

    目的是不再需要输入结构。

    【讨论】:

      【解决方案2】:

      问题是您将结构设为typedef,但仍使用struct 对其进行限定。

      这将起作用:

       employee em1 = {"Jack", 19};
      

      或者删除typedef

      【讨论】:

      • 没有 typedef 它会定义一个结构。它只是缺少一个标签 - typedef struct employee {...} employee;
      【解决方案3】:

      要使用struct employee em1 = ...,您需要使用标签声明结构。

      struct employee /* this is the struct tag */
      {
      char name[20];
      int age;
      } em1, em2; /* declare instances */
      struct employee em3;
      

      typedef 创建一个类型别名,您可以在不使用 struct 关键字的情况下使用它。

      typedef struct employee employee;
      employee em4;
      

      【讨论】:

        【解决方案4】:

        由于您已经对结构进行了 typedef,因此无需再次添加 struct 关键字。

        typedef struct Employee{
            char name[20];
            int age;
        } employee;
        
        int main(int argc, char** argv)
        {
            employee em1 = {"Jack", 19};
            printf("%s", em1.name);
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-19
          • 2016-07-10
          • 1970-01-01
          • 1970-01-01
          • 2012-12-14
          • 1970-01-01
          • 1970-01-01
          • 2020-02-11
          相关资源
          最近更新 更多