KeyWords:struct,malloc,sizeof,struct *,pointer
#include <cstdio>
#include <iostream>
#include <cstdlib>
using namespace std;
struct student{
char name[11];
char number[11];
int score;
};
int main ()
{
int n,i=0;
std::cin >> n;
int max=0,min=100;
int max_pos = 0,min_pos = 0;
struct student *stu;
stu = (struct student*)malloc(sizeof(struct student)*n);
while(n--)
{
cin>>stu[i].name>>stu[i].number>>stu[i].score;
if(stu[i].score > max){
max=stu[i].score;
max_pos= i;
}
if(stu[i].score < min){
min = stu[i].score;
min_pos = i ;
}
i++;
}
cout<<stu[max_pos].name<<" "<<stu[max_pos].number<<endl;
cout<<stu[min_pos].name<<" "<<stu[min_pos].number<<endl;
return 0;
}
Function name: malloc
Full name: memory allocation(内存分配)
Head File: #include stdlib.h 、 #include cstdlib
Original Form:void *malloc(unsigned int size)
- “malloc” VS “new”
malloc和new
new返回指定类型的指针,并且可以自动计算所需要的大小。
int *p;
p = new int;//返回类型为int* ,分配的大小是sizeof(int)
p = new int[100];//返回类型是int*类型,分配的大小为sizeof(int)*100
而malloc需要我们自己计算字节数,并且返回的时候要强转成指定类型的指针。
int *p;
p = (int *)malloc(sizeof(int));