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

这组代码是打印出内容。

相关推荐
加号36 分钟前
【C#】 HTTP 请求通讯实现指南
开发语言·http·c#
Lazionr11 分钟前
【栈与队列经典OJ】
c语言·数据结构
平安的平安18 分钟前
Python实现RAG检索增强生成:让大模型拥有你的私有知识库
开发语言·python
昵称小白20 分钟前
栈与单调栈专题
开发语言·算法
code bean28 分钟前
【LangChain】少样本提示(Few-Shot Prompting)实战指南
开发语言·python·langchain
AI人工智能+电脑小能手30 分钟前
【大白话说Java面试题 第42题】【JVM篇】第2题:JVM内存模型有哪些组成部分?
java·开发语言·jvm·面试
yqcoder31 分钟前
深入理解 JavaScript:什么是可迭代对象 (Iterable)?
开发语言·javascript·网络
破阵子4432835 分钟前
如何用 Claude Code 等 Agent 工具操作 MATLAB(支持代码编写及 Simulink)
开发语言·matlab
AI人工智能+电脑小能手38 分钟前
【大白话说Java面试题 第43题】【JVM篇】第3题:GC分为哪两种?Young GC 和 Full GC有什么区别?
java·开发语言·jvm·后端·面试
Bear on Toilet1 小时前
【JSON-RPC远程过程调用组件库】测试报告
开发语言·软件测试·后端·自动化脚本