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

这组代码是打印出内容。

相关推荐
weixin_4612594125 分钟前
[C]C语言日志系统宏技巧解析
java·服务器·c语言
SteveDraw2 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
十五年专注C++开发2 小时前
设计模式之单例模式(二): 心得体会
开发语言·c++·单例模式·设计模式
flyair_China3 小时前
【云架构】
开发语言·php
Chef_Chen3 小时前
从0开始学习R语言--Day20-ARIMA与格兰杰因果检验
开发语言·学习·r语言
zh_xuan3 小时前
c++ std::pair
开发语言·c++
CodeWithMe3 小时前
【C/C++】EBO空基类优化介绍
开发语言·c++
404.Not Found3 小时前
Day46 Python打卡训练营
开发语言·python
love530love3 小时前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm