typedef与struct用法

1.struct单独使用

struct结构体类型,定义变量时类比于int,char…

#include<stdio.h>

int a;     // 普通变量的定义

struct Student{  // 定义一个结构体
    char s;
    int a;
};

struct Student s;  // 定义一个结构体变量


int main(){


    return 0;
}

注意变量定义的时候不能直接用Student,因为Student只是这个结构体区别于其他结构体的名字,不能用来定义变量;真正用来定义结构体的还是struct关键词。

2.typedef单独使用

typedef相当于给现在的关键词起一个别名。接下来这个别名的作用就相当于原来的关键词了。

#include<stdio.h>

int a;     // 普通变量的定义
typedef int iint;  // 给int起一个别名
iint b = 6;  // 用这个别用定义变量,和int的效果一样

3.typedef和struct连用

在struct用法中我们提到struct Student合起来才能定义变量,所以我们给他用typedef进行重命名。


typedef struct Student{  // 定义一个结构体
    char s;
    int a;
}Stu;   // 吧struct Student重命名为Stu

Stu ss;  // 用Stu定义变量,和下面效果一样

struct Student s;  // 定义一个结构体变量

既然我们可以用一个单词代替两个单词,那么之前的定义方式就用不着了,也就是说我们可以用别名区分每个struct了,那么之前的名字Student就没必要了,于是有了这种简单的写法。

typedef struct{  // 定义一个结构体
    char s;
    int a;
}Stu;   // 吧struct Student重命名为Stu

Stu ss;  // 用Stu定义变量,和下面效果一样

4.数据结构中经常用的struct

在数据结构中用的比较多,举几个栗子。

顺序表:

#include<iostream>
using namespace std;

#define MaxSize 50

typedef struct{
    int data[MaxSize];
    int length;
}SqList;

int main(){
    SqList L;
    L.length = 1;
    L.data[0] = 10;

    return 0;
}

单链表

#include<iostream>
using namespace std;

typedef struct Node{
    int data;
    Node *next;
}Node, *LinkList;

int main(){
    LinkList L = new Node;
    Node node;
    node.data = 10;
    node.next = NULL;
    L->next = &node;
    cout<<node.data<<endl;
    cout<<L->next->data<<endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/C_Ronaldo_/article/details/82932663