struct与typedef struct的区别

一、匿名struct

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

struct {
   int age;
   float weight;
} person;

int main()
{
    struct person *ptr;
    ptr = (struct person*)malloc(sizeof(struct person));
    ptr->age = 10;
    ptr->weight = 55.5;
}

报错error: dereferencing pointer to incomplete type 'struct person',

其实这段代码是申明一个匿名结构体,定义一个叫person的变量

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

struct {
   int age;
   float weight;
} person;

int main()
{
    person.age = 10;
    person.weight = 55.5;
}

这样就ok.

二、struct在C和C++中的区别

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

struct person {
   int age;
   float weight;
};

int main()
{
    person *ptr;
    ptr = (person*)malloc(sizeof(person));
    ptr->age = 10;
    ptr->weight = 55.5;
    printf("%s", "Successful.");
}

这段代码,在C++中没问题,但在C中会编译错误。原因在于C中使用结构体需要struct person.

如下所示:

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

struct person {
   int age;
   float weight;
};

int main()
{
    struct person *ptr;
    ptr = (struct person*)malloc(sizeof(struct person));
    ptr->age = 10;
    ptr->weight = 55.5;
    printf("%s", "Successful.");
}

还有一种方法就是,使用typedef给struct person一个别名。当然,person这个类型名还能用。除外这个别名也可以是person.

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

struct person {
   int age;
   float weight;
};

typedef struct person Person;

int main()
{
    Person *ptr;
    ptr = (struct person*)malloc(sizeof(Person));
    ptr->age = 10;
    ptr->weight = 55.5;
    printf("%s", "Successful.");
}

三、typedef与匿名结构体结合

上面我是将typedef xx  xx写成单独的一行,其实可以与struct的定义结合

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

typedef struct person{
   int age;
   float weight;
}Person;

int main()
{
    Person *ptr;
    ptr = (Person*)malloc(sizeof(Person));
    ptr->age = 10;
    ptr->weight = 55.5;
    printf("%s", "Successful.");
}

这里person其实没有用,因为后面都是用Person,所以我们采用匿名的

typedef struct{
   int age;
   float weight;
}Person;

四、单链表中节点的定义

特点就是结构体里有该结构体类型的指针,例如

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

typedef struct node{
   int value;
   struct node* next;  // 注意,这里必须带struct
}Node, *LinkList;

int main()
{
    Node *ptr;
    ptr = (Node*)malloc(sizeof(Node));
    ptr->value = 1;
    ptr->next = NULL;
    printf("%s", "Successful.");
}

这里Node和LinkList都是类型名,而不是变量名。

Node是节点类型,LinkList是节点指针类型,Node*就等同于LinkList.

 

posted @ 2020-08-04 12:20  Rogn  阅读(554)  评论(0编辑  收藏  举报