typedef 和结构体一起使用的情况

typedef 和结构体一起使用的情况

c语言可以使用下面几种方法定义结构变量

1 结构体

(1)最一般的结构体定义如下(先声明结构类型,再定义变量)

struct student{
    
    
	char name[16];
	char sex;
	float score;
};
struct student stu;    // stu 是变量名

(2)在声明结构的同时定义变量

struct student{
    
    
	char name[16];
	char sex;
	float score;
}stu;           // stu 是变量名

(3) 当结构体和变量名同时定义时,机构标识符是可以省略的

struct {
    
    
	char name[16];
	char sex;
	float score;
}stu;   // stu是变量名

但是这种方式因为没有指定结构标识符,不能在程序的其他位置定义结构变量,因而实际中不常用。可以加上typedef修改成下面

typedef struct {
    
    
	char name[16];
	char sex;
	float score;
}stu;  // stu 是数据类型名称

注意这里的stu不再是变量名,而是数据类型名称,就像int,double等。这里如果不理解没关系,下面会介绍typedef的使用,看完下面回头再看这里就明白了。

2 typedef

typedef <数据类型> <别名>

typedef int zhengshu;
typedef int *zhengshuzhizhen;

下面

int x=1;
int *p;
// 上面两行和下面完全等价
zhengshu x=1;
zhengshuzhizhen p;

3 typedef和struct一起使用的情况

(1)typedef 为结构体定义一个更简单的名字

struct pts{
    
    
	int x;
	int y;
	int z;
};

typedef struct pts Point;   //typedef 为struct pts 定义一个更简单的名字
Point a,b;   // a, b 是变量

(2)也可以组合typedef和结构声明

typedef struct pts{
    
    
	int x;
	int y;
	int z;
}Point;
Point a,b;

现在再看一下之前的那个代码

typedef struct {
    
    
	char name[16];
	char sex;
	float score;
}stu;//stu是数据类型名称

这里因为起了别名,所以可以省略结构标识符
同理

typedef struct {
    
    
	int x;
	int y;
	int z;
}Point;
Point a,b;

省略结构标识符pts
(3) 数据结构中常见下面这种写法

typedef struct CLnode{
    
    
	Elemtype data;
	struct CLnode *next,*prior;
}CLnode,*Linklist; // CLnode 是结构体(结点),Linklist是结构体指针

(4 )还有一种最少见的形式

#define Maxsize 10

typedef struct{
    
    
	int data;
	int next;
	
}Slinklist[Maxsize];

Slinklist b;

Slinklist就指代了一个结构体数组类型,等价于下面这种情况

#include<iostream>
#define Maxsize 10
using namespace std;
typedef struct{
    
    
	int data;
	int next;
}Slinklist[Maxsize];

struct Node{
    
    
	int data;
	int next;
};

void testSlink(){
    
    
	
	struct Node a[MaxSize];
	// 这两个等价
	SlinkList b;
} 

猜你喜欢

转载自blog.csdn.net/m0_52118763/article/details/129541968