C语言学习笔记(21结构体)

1、通过函数完成对结构体变量的输入和输出

/*
通过函数完成对结构体变量的输入和输出
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//定义一个结构体类型
struct Student
{
	int age;
	char sex;
	char name[100];
};
void  InputStudent(struct Student * p);
void  OutPutStudent(struct Student *);//也可以不带形参
int main(void)
{
	struct Student st;
	printf("%d \n",sizeof(st));//st变量占108个字节,而指针变量&st占4个字节。
	//对结构体变量的输入,修改结构体变量的值需要传递变量地址
	InputStudent(&st);
	/*对结构体变量的输出,可以传变量地址也可以传变量
	但是为了减少内存的消耗,也为了提高执行速度,推荐传送变量地址
	*/
	OutPutStudent(&st);
	system("pause");
	return 0;
}

void  InputStudent(struct Student * pst)
{
	(*pst).age=25;//等价于st.age=25;
	strcpy(pst->name,"张三"); //C语言中字符串不能这样赋值pst->name="张三",需要用到字符串拷贝函数
	pst->sex='F';
}
void OutPutStudent(struct Student * pst)
{
	printf("%d %c %s\n",pst->age,pst->sex,pst->name);
}

2、结构体变量的运算


3、冒泡排序

#include <stdio.h>
#include <stdlib.h>
/*
冒泡排序
*/
void Sort(int * pArr,int len);
int main(void)
{
	int a[6]={10,2,8,-8,0,6};
	//a代表数组的首地址
	Sort(a,6);	
	int i=0;
	for(i=0;i<6;i++)
	{
		printf("%d ",a[i]);
	}
	printf("\n");
	system("pause");
	return 0;
}

void Sort(int * pArr,int len)
{
	int i=0;
	int j=0;
	int t=0;
	for(i=0;i<len-1;i++)
	{
		for(j=0;j<len-1-i;j++)
		{
			if(pArr[j]>pArr[j+1])
			{
				t=pArr[j];
				pArr[j]=pArr[j+1];
				pArr[j+1]=t;
			}	
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值