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

这组代码是打印出内容。

相关推荐
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329292 天前
Day03_刷题niuke20250915
c语言
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_2 天前
QT(4)
开发语言·汇编·c++·qt·算法