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;
}
}
}
}