申请的内存管理是可以被返回的
// ConsoleApplication9.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
#include <stdlib.h>
using namespace std;
struct Student
{
int number; //xuehao
char name[1024];
double yuwen;
double shuxue;
double yingyu;
};
class MyClass
{
public:
MyClass();
~MyClass();
private:
};
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
int *description;
int *cinmyArray(int array[])
{
cout << "请输入10个数字" << endl;
description = (int *)malloc(10 * sizeof(int));
if (description == NULL)
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
for (int i = 0; i < 10; i++)
{
cin >> description[i];
}
}
cout << "输入完毕" << endl;
return description;
}
int *sortMyArray(int *description)
{
for (int i = 0; i<10; i++) {
for (int j = i + 1; j<10; j++) {
if (description[i]>description[j]) {//若前一个元素比后一个元素大,则借助临时变量temp交换(此排序为升序排序,若为降序排序则为arr[i]<arr[j])
int temp = description[i];
description[i] = description[j];
description[j] = temp;
}
}
}
return description;
}
void adjust(int a[], int n)
{
for (int i = 0; i<n; i++)
{
//找最大值
if (i % 2 == 0)
{
int j = i + 1;
//记录最大值的位置
int loc = i;
for (; j<n; j++)
{
if (a[j]>a[loc])loc = j;
}
//发生交换
if (loc != i)
{
int temp = a[loc];
a[loc] = a[i];
a[i] = temp;
}
}
//找最小值
else
{
int j = i + 1;
//记录最小值的位置
int loc = i;
for (; j<n; j++)
{
if (a[j]<a[loc])loc = j;
}
//发生交换
if (loc != i)
{
int temp = a[loc];
a[loc] = a[i];
a[i] = temp;
}
}
}
}
int *coutMyArray(int *description)
{
for (int i = 0; i < 10; i++)
{
cout << description[i] << endl;
}
return description;
}
int _tmain(int argc, _TCHAR* argv[])
{
/*
有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),
计算出平均成绩,
况原有的数据和计算出的平均分数存放在磁盘文件"stud"中。*/
/*
cout << "请输入5个学生的成绩" << endl;
Student mStudent[5];
for (int i = 0; i < 5; i++)
{
cout << "请输入" << i + 1 << "个学生的学号" << endl;
cin >> mStudent[i].number;
cout << "请输入" << i + 1 << "个学生的姓名" << endl;
cin >> mStudent[i].name;
cout << "请输入" << i + 1 << "个学生的语文成绩" << endl;
cin >> mStudent[i].yuwen;
cout << "请输入" << i + 1 << "个学生的数学成绩" << endl;
cin >> mStudent[i].shuxue;
cout << "请输入" << i + 1 << "个学生的英语成绩" << endl;
cin >> mStudent[i].yingyu;
}
for (int i = 0; i < 5; i++)
{
cout << mStudent[i].number << "," << mStudent[i].name << "," << mStudent[i].yuwen << "," << mStudent[i].shuxue << "," << mStudent[i].yingyu << endl;
}
*/
int myArray[10] = { 0 };
FILE*fp;
cinmyArray(myArray);
sortMyArray(description);
coutMyArray(description);
cout << "*************" << endl;
adjust(description, 10);
coutMyArray(description);
if ((fp = fopen("stud", "w")) == NULL)
{
printf("error :cannot open file!\n");
exit(0);
}
for (int i = 0; i<10; i++)
fprintf(fp, "%d\n", description[i]);
fclose(fp);
if (description != nullptr) {
free(description);
cout << "内存清理完毕" << endl;
}
return 0;
}