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

这组代码是打印出内容。

相关推荐
ShineWinsu20 小时前
对于C++:继承的解析—上
开发语言·数据结构·c++·算法·面试·笔试·继承
小付同学呀21 小时前
C语言学习(五)——输入/输出
c语言·开发语言·学习
梦幻精灵_cq21 小时前
学C之路:不可或缺的main()主函数框架(Learn-C 1st)
c语言·开发语言
消失的旧时光-194321 小时前
C++ 多线程与并发系统取向(二)—— 资源保护:std::mutex 与 RAII(类比 Java synchronized)
java·开发语言·c++·并发
福大大架构师每日一题1 天前
go-zero v1.10.0发布!全面支持Go 1.23、MCP SDK迁移、性能与稳定性双提升
开发语言·后端·golang
五阿哥永琪1 天前
1. 为什么java不能用is开头来做布尔值的参数名,会出现反序列化异常。
java·开发语言
逻极1 天前
pytest 入门指南:Python 测试框架从零到一(2025 实战版)
开发语言·python·pytest
你的冰西瓜1 天前
C++ STL算法——排序和相关操作
开发语言·c++·算法·stl
海边的Kurisu1 天前
Mybatis-Plus | 只做增强不做改变——为简化开发而生
java·开发语言·mybatis
浅念-1 天前
C++ 模板进阶
开发语言·数据结构·c++·经验分享·笔记·学习·模版