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);

这组代码是打印出内容。

相关推荐
zhangfeng11334 分钟前
PowerShell 中不支持激活你选中的 Python 虚拟环境,建议切换到命令提示符(Command Prompt)
开发语言·python·prompt
huizhixue-IT8 分钟前
2026年还需要学习RHCE 吗?
开发语言·perl
zUlKyyRC14 分钟前
LabVIEW 玩转数据库:Access 与 SQL Server 的实用之旅
开发语言
方便面不加香菜25 分钟前
数据结构--栈和队列
c语言·数据结构
AGMTI31 分钟前
webSock动态注册消息回调函数功能实现
开发语言·前端·javascript
csbysj20201 小时前
SQLite Select 语句
开发语言
点云SLAM1 小时前
C++(C++17/20)最佳工厂写法和SLAM应用综合示例
开发语言·c++·设计模式·c++实战·注册工厂模式·c++大工程系统
_WndProc1 小时前
【Python】方程计算器
开发语言·python
会游泳的石头1 小时前
Java 异步事务完成后的监听器:原理、实现与应用场景
java·开发语言·数据库
黎雁·泠崖1 小时前
Java字符串进阶:StringBuilder+StringJoiner
java·开发语言