结构体学习(2)

上次提到结构体和数组,指针结合会显得更有其作用。今天的学习内容就为结构体数组。

其实定义的结构体变量就如数组一般。

struct student
{
    
    
	int num;
	char *name;
	char sex;
	float score;
}boy1,boy2={
    
    102,"jane",'M',98.5};

就如这段代码,对boy2的初始化。

注意
结构体数组与以前介绍过的数值型数组不同之处在于每个数组元素都是一个结构体类型的数据,它们都分别包括各个成员(分量)项。

如用结构体数组,完成通讯录功能。

#include<stdio.h>
#include<stdlib.h>
#define num 3
struct persons 
{
    
    
	char name[20];
	char phonenumbers[20];
}h[num];
int main()
{
    
    
	int i;

	for(i=0;i<num;i++)
	{
    
    
		printf("input name\n");
		gets(h[i].name);
		printf("input phonenumbers\n");
		gets(h[i].phonenumbers);
	}
	printf("\tname\t\t\t\t\tphone\n\n");

	for(i=0;i<num;i++)
	{
    
    
		printf("%20s\t\t\t%20s\n",h[i].name,h[i].phonenumbers);
	}
}

初见结构体数组功能。

可以以下方式进行初始化。
struct student str[]{ {…},{…},{…}};

接下来会进行结构体数组实践。内容看似不多,但编程题难度不小。

猜你喜欢

转载自blog.csdn.net/yooppa/article/details/112547455