数据结构day1

本文展示了如何在C语言中使用选择排序算法对包含成绩和姓名的结构体数组进行排序,涉及内存分配和数据交换操作。
摘要由CSDN通过智能技术生成
  1. 从堆区申请能存5个结构体变量的数组的空间,完成数组中成员的输入,根据学生成绩,用选择排序的方式,对学生排序并输出。
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    struct stu
    {
    	char name[20];
    	int score;
    };
    int main(int argc, const char *argv[])
    {
    	struct stu *p=(struct stu*)malloc(sizeof(struct stu)*5);
    	for(int i=0;i<5;i++)
    	{
    		printf("person %d \n",i);
    		printf("score : ");
    		scanf("%d",&(p+i)->score);
    		printf("name : ");
    		getchar();
    		gets((p+i)->name);
    	}
    	for(int i=0;i<4;i++)
    		for(int j=i+1;j<5;j++)
    		{
    			if((p+i)->score<(p+j)->score)
    			{
    				char temp[20]="";
    				strcpy(temp,(p+j)->name);
    				strcpy((p+j)->name,(p+i)->name);
    				strcpy((p+i)->name,temp);
    				int temp1;
    				temp1=(p+j)->score;
    				(p+j)->score=(p+i)->score;
    				(p+i)->score=temp1;
    			}
    		}
    	printf("After sort:\n");
    		for(int i=0;i<5;i++)
    	{
    		printf("name : ");
    		puts((p+i)->name);
    		printf("score : %d\n",(p+i)->score);
    	}
    
    	return 0;
    }
    

  2. 求以下结构体的大小

typedef struct {
    int id;
    char name[50];
    char grade[3];
} Student;
 大小为60
typedef struct {
    int id;
    char name[50];
    Student student;
} Teacher; 

大小为116

typedef struct {
    int id;
    char name[50];
    Teacher teacher;
} Course;

大小为172

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值