struct和typedef struct区别,struct的用法

1.在C语言中,struct关键字用于定义结构体,而typedef关键字用于为数据类型提供别名。

//以 struct Name_A 定义结构体
struct Name_A		
{
    
};

//以 struct Name_A 定义结构体,在申请新的 Name_A 变量时需要下面的写法
struct Name_A Name1;

//==============================================================

//以 typedef struct Name_B 定义结构体
typedef struct Name_B
{
    
}Name_C;

//以 typedef struct Name_B 定义结构体,在申请新的 Name_B 变量时可以省略 struct	
//Name_C是 Name_B 的别名

Name_B Name1;		//这两个写法都是对的
Name_C Name1;


代码:

//struct写法
struct Name_A
{
	int Green;
	int Red;
	int Blue;
};

struct Name_A Array[5]
{
	{10, 15, 20},
	{1, 3, 5},
	{36, 60, 90},
	{22, 32, 42},
	{3, 6, 9}
};


//=================================================================================================

//typedef struct写法
typedef struct Name_B
{
	int Green;
	int Red;
	int Blue;
}Name_C;


Name_B Array[5] =
{
	{10, 15, 20},
	{1, 3, 5},
	{36, 60, 90},
	{22, 32, 42},
	{3, 6, 9}
};

Name_C Array[5] =
{
	{10, 15, 20},
	{1, 3, 5},
	{36, 60, 90},
	{22, 32, 42},
	{3, 6, 9}
};

2.在c++中可以不需要typedef就可以Name_A Name1,因为在c++中struct也是一种类,所以可以直接使用Name_A Name1来定义一个Name_A的对象,但c中却不可以。

struct Name_A
{
	int Green;
	int Red;
	int Blue;
};

Name_A Array[5]
{
	{10, 15, 20},
	{1, 3, 5},
	{36, 60, 90},
	{22, 32, 42},
	{3, 6, 9}
};


typedef struct Name_B
{
	int Green;
	int Red;
	int Blue;
}Name_C;


Name_B Array[5] =
{
	{10, 15, 20},
	{1, 3, 5},
	{36, 60, 90},
	{22, 32, 42},
	{3, 6, 9}
};

Name_C Array[5] =
{
	{10, 15, 20},
	{1, 3, 5},
	{36, 60, 90},
	{22, 32, 42},
	{3, 6, 9}
};

3.结构体定义和使用

语法:struct 结构体名 { 结构体成员列表 }
通过结构体创建变量的方式有三种:
  • struct 结构体名 变量名

  • struct 结构体名 变量名 = { 成员1值 , 成员2值…}

  • 定义结构体时顺便创建变量

    //结构体定义
    struct Name_A
    {
    	//成员列表
    	string name;  //姓名
    	int age;      //年龄
    	int score;    //分数
    }Name3; //结构体变量创建方式3 
    
    int main() 
    {
    
    	//结构体变量创建方式1	C中:struct 关键字不可以省略		C++中:struct 关键字可以省略
    	struct Name Name1; 
    
    	Name1.name = "张三";
    	Name1.age = 18;
    	Name1.score = 100;
        
        //================================================================================
    	
        //结构体变量创建方式2 	C中:struct 关键字不可以省略		C++中:struct 关键字可以省略
    	struct Name_A Name2 = { "李四",19,60 };													
    
    	Name3.name = "王五";
    	Name3.age = 18;
    	Name3.score = 80;
    	
    }
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值