结构体与共用体
用指向结构体变量的指针表示下列结构体数
组元素:
struct student {
int num;
char name;
char sex; int age;
char addr;
} ;
struct student stu={
{111,”Li”,’M’,18,”Dalian”},
{222, “Wang”, ‘F’, 20, “Shenyang”},
{333, “zhang”, ‘M’, 19, “Beijing”}
}; 本帖最后由 jackz007 于 2022-11-23 15:38 编辑
#include <stdio.h>
struct student {
int num ;
char name ;
char sex ;
int age ;
char addr ;
} ;
int main(void)
{
struct student stu = {{111,"Li",'M',18,"Dalian"} ,
{222, "Wang", 'F', 20, "Shenyang"} ,
{333, "zhang", 'M', 19, "Beijing"}} ;
struct student * p = stu ;
int i ;
for(i = 0 ; i < 3 ; i ++) {
printf("%d\t%s\t%c\t%d\t%s\n" , p -> num , p -> name , p -> sex , p -> age , p -> addr) ;
p ++ ;
}
} 本帖最后由 竹逸 于 2022-11-23 16:07 编辑
#include<stdio.h>
struct student
{
int num;
char name;
char sex;
int age;
char addr;
};
void main()
{
int i;
struct student stu = {{111, "Li", 'M', 18, "Dalian"}, {222, "Wang", 'F', 20, "Shenyang"}, {333, "zhang", 'M', 19, "Beijing"}};
struct student (*p) = &stu;
printf("num name sex age addr\n\n");
for(i=0 ; i<3 ; i++)
{
printf("%-9d%-11s%-7c%-9d%s\n", (*((*p) + i)).num, (*((*p) + i)).name, (*((*p) + i)).sex,(*((*p) + i)).age,(*((*p) + i)).addr);
}
putchar('\n');
}
循环体这样也行
for(i=0 ; i<3 ; i++)
{
printf("%-9d%-11s%-7c%-9d%s\n", ((*p) + i)->num, ((*p) + i)->name,
((*p) + i)->sex,((*p) + i)->age, ((*p) + i)->addr);
} 其实我这代码的效率没jackz007大佬高,我用的是二级指针,凭白的多了一次寻址的过程,多此一举了
页:
[1]