简体   繁体   English

我可以将 typedef 结构与指针一起使用吗?

[英]Can I use my typedef structure with pointer?

Here I wrote some code with a pointer to a structure.在这里,我编写了一些带有指向结构的指针的代码。 I put in some typedef but I don't know how to use it with my pointer structure.我输入了一些typedef ,但我不知道如何将它与我的指针结构一起使用。 I can't find any help on the internet.我在互联网上找不到任何帮助。 Always typedef structure, or pointer structure, but not with these 3 involved.总是 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);

}
#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);

}

I found the solution, I just removed the "struct" and left the student in, works fine, thannks for the help我找到了解决方案,我刚刚删除了“结构”并将学生留在里面,工作正常,感谢您的帮助

The so-called name space rules of C are a bit confusing. C 的所谓命名空间规则有点混乱。 When it comes to structs there are 3 different ones that apply: struct tag, struct member and ordinary identifiers.当涉及到结构时,有 3 种不同的适用:结构标记、结构成员和普通标识符。

  • struct student is a struct tag. struct student是一个结构标签。
  • typedef... }student; is an ordinary identifier (like any variable name).是一个普通的标识符(就像任何变量名一样)。

Since these exist in different name spaces, we can use the same identifier.由于它们存在于不同的名称空间中,我们可以使用相同的标识符。 When you type struct student in your code, you refer to the struct by tag, if you just type student then the ordinary identifier.当您在代码中输入struct student时,您通过标签引用该结构,如果您只输入student则为普通标识符。 As you can tell it gets very confusing when they are given the same name, so we shouldn't do that.正如你所知道的,当它们被赋予相同的名称时会变得非常混乱,所以我们不应该这样做。

How to declare structs is otherwise a style issue with no obvious right or wrong.否则,如何声明结构是一个没有明显对错的样式问题。 The Linux world uses the struct name {... }; Linux 世界使用struct name {... }; style with struct tags.带有结构标签的样式。 The rest of the world uses the typedef struct {... } name;世界的rest使用typedef struct {... } name; style.风格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM