【问题标题】:Can I use my typedef structure with pointer?我可以将 typedef 结构与指针一起使用吗?
【发布时间】:2021-08-01 11:48:48
【问题描述】:

在这里,我编写了一些带有指向结构的指针的代码。我输入了一些typedef,但我不知道如何将它与我的指针结构一起使用。我在互联网上找不到任何帮助。总是 typedef 结构,或指针结构,但不涉及这 3 个。

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

typedef struct student{
    char NAME[20];
    int ID;
    float GRADE;
    char INSTRUCTOR[20];
}student;


int main()
{
    struct student Raf = {"Rafael Sunga", 1775, 1.35, "Kenneth Auxillos"};
    struct student *ptr_Raf; //declaring ptr to a structure
    ptr_Raf = &Raf; //asigning address of variable with & 
    
    printf("Student Name: %s\n", ptr_Raf->NAME);
    printf("ID: %d\n", ptr_Raf->ID);
    printf("Grade: %.2f\n", ptr_Raf->GRADE);
    printf("Instructor: %s\n", ptr_Raf->INSTRUCTOR);

}

【问题讨论】:

  • 请描述您怀疑的原因。
  • 我不确定你在问什么。这段代码不适合你吗?
  • 1 指针类型定义。 2 结构指针。第三个是什么?
  • 如果我没听错的话,你想定义一个类型,它已经是一个指针。这可以通过typedef struct {} student, *pstudent; 实现,但你永远不应该这样做。在 typedef 中隐藏指针被认为是不好的做法。
  • 显示的代码没有使用typedef名称student;它只使用结构标签struct student。您可以将struct student 中的一个或两个替换为student 内的main(),并且代码的含义不会改变。请注意,在成员名称中使用全大写是不常见的;全大写符号通常保留给宏和枚举常量。对结构成员名称使用小写或混合大小写的名称。

标签: c pointers struct typedef


【解决方案1】:
#include<stdio.h>
#include<stdlib.h>

typedef struct student //old data type
{
    char NAME[20];
    int ID;
    float GRADE;
    char INSTRUCTOR[20];
}student; //new data type


int main()
{
    student Raf = {"Rafael Sunga", 1775, 1.35, "Kenneth Auxillos"};
    student *ptr_Raf; //declaring ptr to a structure
    ptr_Raf = &Raf; //asigning address of variable with & 
    
    printf("Student Name: %s\n", ptr_Raf->NAME);
    printf("ID: %d\n", ptr_Raf->ID);
    printf("Grade: %.2f\n", ptr_Raf->GRADE);
    printf("Instructor: %s\n", ptr_Raf->INSTRUCTOR);

}

我找到了解决方案,我只是删除了“结构”并将学生留在里面,工作正常,感谢您的帮助

【讨论】:

    【解决方案2】:

    C 的所谓命名空间规则有点混乱。当涉及到结构时,有 3 种不同的适用:结构标记、结构成员和普通标识符。

    • struct student 是一个结构体标签。
    • typedef ... }student; 是一个普通的标识符(就像任何变量名一样)。

    由于它们存在于不同的名称空间中,我们可以使用相同的标识符。当您在代码中键入struct student 时,您通过标记引用结构,如果您只键入student,则为普通标识符。正如你所看到的,当它们被赋予相同的名字时会变得非常混乱,所以我们不应该这样做。

    如何声明结构体是一个没有明显对错的样式问题。 Linux 世界使用带有结构标签的struct name { ... }; 样式。世界其他地方使用typedef struct { ... } name; 样式。

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 2021-03-09
      相关资源
      最近更新 更多