在以下计划中,
int * accepted_ids = (int *) malloc(sizeof(int)*N);
double * accepted_scores = (double *)malloc(sizeof(double)*N);
int * unaccepted_ids = (int *) malloc(sizeof(int)*N);
double * unaccepted_scores = (double *) malloc(sizeof(double)*N);
这些内存分配正在为每个内存分配创建大小为N
的数组,即使所需元素的数量远远低于N
的数量。
由于程序使用的是随机数生成器,我们无法事先告诉我们每个内存需要多少内存。
我该如何解决这个难题?
(最多5分)
单维数组SCORES存储得分 他们在高中时获得了N个大学候选人。元素索引 数组是这些候选者的ID。大学接受 来自平均分数大于或等于的候选人的申请 到4.0。编写一个显示的简短程序:
•已接受候选人名单及其身份证号码及其平均分数。 •未接受的候选人名单及其身份证号码 平均分 •接受和未接受的候选人数量。 •结果排序 按升序排列
应计算平均分数 从范围< 2,6>使用随机数发生器。总人数 候选人应该作为命令行参数传递给程序。 使您的程序对错误参数的输入敏感。
不允许使用struct。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
// This function tests whether it is possible
// to convert a string into integer or not.
//
// This function is needed to check the
// input argument otherwise if you type
// C:\>myapp.exe abc
// your program will crash.
int is_integer(const char * s)
{
char * endptr;
int radix = 10;//decimal number system
// try to convert s to integer
strtol(s, &endptr, radix);
errno = 0;
// if this conditions are fullfilled,
// that means, s can't be converted
// to an integer.
if (endptr == s || *endptr != '\0')
{
// argument must be an integer value
return 0; // failure
}
if (errno == ERANGE)
{
// int argument out of range
return 0; // failure
}
return 1; //success
}
// This function is needed to convert
// a string to an integer value.
int string_to_integer(const char * s)
{
char * endptr;
int radix = 10;//decimal number system
// convert s to integer
return strtol(s, &endptr, radix);
}
// Generte a random number between M and N.
//
// This function is needed coz rand() can
// generate only integer values.
double round_between_m_to_n(double M, double N)
{
return M + (rand() / (RAND_MAX / (N - M)));
}
// This is Bubble sort algorithm
// This is implemented as a user-defined function,
// coz, you have to use this twice.
// First for accepted scores,
// then for unaccepted scores.
void sort(int * ids, double * scores, int count)
{
for (int i = 0; i < count; i++)
{
for (int j = 0; j < i; j++)
{
if (scores[i] < scores[j])
{
// Swap scores
double temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
// Swap ids
int temp2 = ids[i];
ids[i] = ids[j];
ids[j] = temp2;
}
}
}
}
// This function is to print ids and scores
// as a table.
// This is implemented as a user-defined function,
// coz, you have to use this twice.
// First for accepted scores,
// then for unaccepted scores.
void print(int * ids, double * scores, int count)
{
printf("id\tavg_score\n");
printf("-------------------\n");
for (int i = 0; i < count; i++)
{
printf("%i\t%.1f\n", ids[i], scores[i]);
}
}
int main(int argc, char ** argv)
{
// Program can proceed only if
// the # of arguments is exactly 2.
// The 1st arg is always app-name.
if (argc != 2)
{
printf("insufficient argument\n");
return EXIT_FAILURE;
}
int N = 0;
int accepted_scores_count = 0;
int unaccepted_scores_count = 0;
double acceptance_threshhold = 4.0;
if (!is_integer(argv[1]))
{
printf("incorrect argument type\n");
return EXIT_FAILURE;
}
else
{
N = string_to_integer(argv[1]);
printf("Total %d students\n", N);
}
// Pair of variables are needed to
// keep track of student-ids.
// Otherwise, you can't tell what id a
// student has when data are sorted.
int * accepted_ids = (int *)malloc(sizeof(int)*N);
double * accepted_scores = (double *)malloc(sizeof(double)*N);
int * unaccepted_ids = (int *)malloc(sizeof(int)*N);
double * unaccepted_scores = (double *)malloc(sizeof(double)*N);
//Initialize random seed.
//If you don't use this, rand() will generate
//same values each time you run the program.
srand(time(NULL));
// Simultaneously generate scores, ids, and
// store them is sepaerate arrays.
for (int i = 0; i < N; i++)
{
int id = i;
double score = round_between_m_to_n(2, 6);
// if the score is greater than or
// equal to 4.0...
if (score >= acceptance_threshhold)
{
accepted_ids[accepted_scores_count] = i;
accepted_scores[accepted_scores_count] = score;
accepted_scores_count++;
}
// ... otherwise they are unaccepted.
else
{
unaccepted_ids[unaccepted_scores_count] = i;
unaccepted_scores[unaccepted_scores_count] = score;
unaccepted_scores_count++;
}
}
// sort accepted students
sort(accepted_ids, accepted_scores, accepted_scores_count);
// sort unaccpeted students
sort(unaccepted_ids, unaccepted_scores, unaccepted_scores_count);
// print accepted students
printf("\naccepted students\n");
print(accepted_ids, accepted_scores, accepted_scores_count);
// print unaccepted students
printf("\nunaccepted students\n");
print(unaccepted_ids, unaccepted_scores, unaccepted_scores_count);
printf("\nEnd of program.\n");
free(accepted_ids);
free(accepted_scores);
free(unaccepted_ids);
free(unaccepted_scores);
return EXIT_SUCCESS;
}
答案 0 :(得分:1)
如果您想最终分配更少的内存,请使用realloc。首先重新分配0项,然后每次需要分配更多项时,使用realloc分配更多内存。由于realloc将复制&#39;现有数据,您只会得到实际需要的内存。请记住,realloc不是一个很好的功能,它的使用应该小心,因为它很容易出错(确保检查返回值,并在覆盖指针之前跟踪以前的分配) )。
答案 1 :(得分:1)
因为您知道为其生成数据的学生人数,您可以使用所有学生的数据数组:
int * all_ids = (int *)malloc(sizeof(int)*N);
double * all_scores = (double *)malloc(sizeof(int)*N);
然后正常生成数据,保持计数,但将数据分配到all_*
数组:
for (int i = 0; i < N; i++)
{
int id = i;
double score = round_between_m_to_n(2, 6);
all_ids[i] = id;
all_scores[i] = score;
// if the score is greater than or
// equal to 4.0...
if (score >= acceptance_threshhold)
{
accepted_scores_count++;
}
// ... otherwise they are unaccepted.
else
{
unaccepted_scores_count++;
}
}
因为您知道区分已接受学生的阈值,您可以稍后拆分。
现在您拥有所有数据,以及被接受但未被接受的学生人数。使用此信息,您可以为已接受和未接受的学生分配数组:
int * accepted_ids = (int *)malloc(sizeof(int) * accepted_scores_count);
double * accepted_scores = (double *)malloc(sizeof(double) * accepted_scores_count);
int * unaccepted_ids = (int *)malloc(sizeof(int) * unaccepted_scores_count);
double * unaccepted_scores = (double *)malloc(sizeof(double) * unaccepted_scores_count);
使用for
循环(减去数据生成,因为完成后)将数据按原样排序为已接受和未接受的数组:
for (int i = 0, j = 0; (i+j) < N;)
{
int id = all_ids[i+j];
double score = all_scores[i+j];
// if the score is greater than or
// equal to 4.0...
if (score >= acceptance_threshhold)
{
accepted_ids[i] = id;
accepted_scores[i] = score;
i++;
}
// ... otherwise they are unaccepted.
else
{
unaccepted_ids[j] = id;
unaccepted_scores[j] = score;
j++;
}
}
之后,您可以继续正常排序和打印数据。您必须记住也要释放all_*
数组。