42 date:2021.3.21
要点:
calloc 用于分配内存空间,形式: (类型说明符)calloc(n,size)
在内存动态存储区中分配n块长度为"size"字节的连续区域,函数的返回值为该区域的首地址
(类型说明符*)用于强制类型转换。
calloc函数与malloc函数的区别在于calloc函数一次可以分配n块区域
详细代码如下:
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#define N 10
typedef struct ss
{ char num[10];
int s;
} STU;
STU *fun(STU a[], int m)
{ STU b[N],*t;
int i, j,k;
/*************found**************/
t=(STU*)calloc(m,sizeof(STU));
for(i=0;i<N;i++) b[i]=a[i];
for(k=0;k<m;k++)
{ for (i=j=0;i<N;i++)
if(b[i].s>b[j].s) j=i;
/*************found**************/
strcpy(t[k].num,b[j].num); //因为num是数组类型,所以不可以直接用t[k].num = b[j].num这种赋值办法
t[k].s=b[j].s;
b[j].s=0;
}
return t;
}
void outresult(STU a[],FILE *pf)
{ int i;
for(i=0;i<N;i++)
fprintf(pf, "No=%s Mark=%d\n ",
a[i].num, a[i].s);
fprintf(pf, "\n\n ");
}
void main()
{ STU a[N]={{ "A01 ",81},{ "A02 ",89},{ "A03 ",66},{ "A04 ",87},{ "A05 ",77},
{ "A06 ",90},{ "A07 ",79},{ "A08 ",61},{ "A09 ",80},{ "A10 ",71}};
STU *pOrder;
int i, m;
system("CLS");
printf("*****THE RESULT*****\n");
outresult(a,stdout);
printf("\nGive the number of the students who have better score: ");
scanf("%d",&m);
while(m>10)
{ printf("\nGive the number of the students who have better score: ");
scanf("%d",&m);
}
pOrder=fun(a,m);
printf("***** THE RESULT*****\n");
printf("The top :\n");
for(i=0;i<m;i++)
printf("%s %d\n",pOrder[i].num, pOrder[i].s);
free(pOrder);
}
要点:
注意下标
详细代码如下:
#include <stdio.h>
#define N 80
int fun(int a[], int n)
{
/*
analyse:
*/
int i , j = 1;
for(i = 1; i<n; i++)
{
if(a[i] != a[i-1]) //若该数与前一个数不相同,则要保留
a[j++] = a[i];
}
return j; //返回不相同的个数
/*
int i,j=0;
for(i = 0; i<20; i++)
{
if(a[i] == a[i+1])
a[j] =a[i];
}
*/
}
void main()
{
FILE *wf;
int a[N]={ 2,2,2,3,4,4,5,6,6,6,6,7,7,8,9,9,10,10,10,10}, i, n=20;
printf("The original data :\n");
for(i=0; i<n; i++)
printf("%3d",a[i]);
n=fun(a,n);
printf("\n\nThe data after deleted :\n");
for(i=0; i<n; i++)
printf("%3d",a[i]);
printf("\n\n");
/******************************/
wf=fopen("out.dat","w");
for(i=0; i<n; i++)
fprintf(wf,"%3d",a[i]);
fclose(wf);
/*****************************/
}