自学内容网 自学内容网

c语言之指针指向结构体数组

在c语言中,指针指向结构体数组的方法是

在定义一个结构体数组之后,定义一个结构体指针

通过数组地址增减来控制在哪个数组元素

示例代码如下

#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);
这组代码是打印出内容。


原文地址:https://blog.csdn.net/2301_81968528/article/details/137891981

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!