结构体变量的定义

文章介绍了C语言中结构体的四种定义方式,包括同时定义结构体和变量、直接定义变量、先定义类型后定义变量以及结构体成员为其他结构体的情况。同时,通过示例展示了结构体变量成员的初始化及使用,并指出结构体成员名可以与其他变量名相同但并不冲突。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.同时定义结构体和结构体变量

struct Student
{
  int id;
  char name[10];
  int age;
}stu1,stu2;//定义结构体变量stu1和stu2

2.直接定义结构体变量

struct          //不写结构体名
{
  int id;
  char name[10];
  int age;
}stu1,stu2;

3.先定义结构体类型后定义结构体变量

struct Student
{
  int id;
  char name[10];
  int age;
};
void main()
{
  struct Student stu1,stu2;
  return 0;
}

4.结构体变量中的成员也是一个结构体变量

struct date
{
  int year;
  int month;
  int day;
};
struct Student
{
  char name[10];
  int id;
  struct date;      //date为结构体类型,那么它的变量就是母结构体的成员变量
}stu1,stu2;
struct Student
{
  char name[10];
  int id;
  struct date
  {
    int year;
    int month;
    int day;
  }a1;    //内部定义的第一种形式
  struct date a2;   //内部定义的第二种形式   
}stu1,stu2;

以上是两种形式的定义

另外结构体中的成员名可以和其他变量名相同,二者不是同一个变量

#include <stdio.h>
struct Student
{
  int id;
  char name[10];
  int age;
}stu1,stu2;//定义结构体变量stu1和stu2
int main () 
{
	char id='m';
	struct Student stu1={10086,"Tom",18};
	printf("%d\n",stu1.id);
	printf("%c",id);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值