c语言之指针指向结构体数组

在c语言中,指针指向结构体数组的方法是

在定义一个结构体数组之后,定义一个结构体指针

通过数组地址增减来控制在哪个数组元素

示例代码如下

cpp 复制代码
#include<stdio.h>
int main()
{
	struct test
	{
	char name[30];
	int age;
	char sex;
	int student_number;
	} student[3];
	struct test *p;

	for(p=student;p<student+3;p++)
	{
		printf("请输入姓名 年龄 性别 学号:");
		scanf("%s %d %c %d",p->name,&(p->age),&(p->sex),&(p->student_number));
	}
	for(p=student;p<student+3;p++)
		printf("姓名:%s\t 年龄:%d\t 性别:%c\t 学号:%d\n",p->name,p->age,p->sex,p->student_number);

	return 0;
}

首先是定义一个结构体数组student[3]

用一个for循环不断输入信息

for(p=student;p<student+3;p++)

{

printf("请输入姓名 年龄 性别 学号:");

scanf("%s %d %c %d",p->name,&(p->age),&(p->sex),&(p->student_number));

}

指针p指向数组student的第一个地址,然后p的值小于student数组的第四个地址时,p的值加1.在数组指针中,指针值+1是指向下一个数组元素的地址。

for(p=student;p<student+3;p++)

printf("姓名:%s\t 年龄:%d\t 性别:%c\t 学号:%d\n",p->name,p->age,p->sex,p->student_number);

这组代码是打印出内容。

相关推荐
不吃香菜学java8 小时前
Redis的java客户端
java·开发语言·spring boot·redis·缓存
贵沫末9 小时前
python——打包自己的库并安装
开发语言·windows·python
文祐9 小时前
C++类之虚函数表及其内存布局(一个子类继承一个父类)
开发语言·c++
zuowei28899 小时前
华为网络设备配置文件备份与恢复(上传、下载、导出,导入)
开发语言·华为·php
xiaohe0710 小时前
超详细 Python 爬虫指南
开发语言·爬虫·python
嗑嗑嗑瓜子的猫10 小时前
Java!它值得!
java·开发语言
xiaoshuaishuai810 小时前
C# GPU算力与管理
开发语言·windows·c#
lsx20240610 小时前
SVN 创建版本库
开发语言
xiaotao13110 小时前
01-编程基础与数学基石:Python错误与异常处理
开发语言·人工智能·python
glimix11 小时前
Word-Pop:使用C语言开发打单词游戏
c语言·游戏