Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save s3f/ba22038b339263e21e48edd985366c70 to your computer and use it in GitHub Desktop.
Save s3f/ba22038b339263e21e48edd985366c70 to your computer and use it in GitHub Desktop.
Chapter 26- Maximizing Your Computer's Memory created by s3f - https://repl.it/FESr/8
// Heap Memory
/*
The heap is a collection of unused memory in the computer. You usually want to access the heap because your program will need more memory than you initially defined in the variables and arrays. The only way to access heap memory is through pointer variables.
The heap anables your program to use only as much memory as it needs. When the user needs more memory, your program can allocate the memory. When the user is fisnished using the certain amount of memory, you can deallocate the memory, making it available for other tasks that might need it.
How do you allocate the heap? There are two functions you need to know:
malloc() --> Allocates Heap memory
free() --> Deallocates heap memory
The following program below looks for a randon mumber of random integers, allocates an array of files it numbers beween 1 and 500 and then loops through all the numbers and figures out the smallest, the biggest, and then the average. At the end, it frees the memory.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
int i, aSize;
int* randomNums;
time_t t;
double total = 0;
int biggest, smallest;
float average;
srand(time(&t));
printf("How many random numbers would you like in your array? ");
scanf(" %d", &aSize);
/* Allocates an array of integers equal to the number of elements requested by the user */
randomNums = (int*)malloc(aSize * sizeof(int));
// test to ensure that the array allocated properly
if (!randomNums)
{
printf("Random array allocation failed!\n");
exit(1);
}
// Loops through the array and assigns a random number between 1 - 500
for (i = 0; i < aSize; i++)
{
randomNums[i] = (rand() % 500) + 1;
}
// Initialize the biggest and smallest number for comparison's sake
biggest = 0;
smallest = 500;
/*
Now we loop through the now-filled array, testing for the random numbers that are biggest,
smallest, and adding all numbers together to calculate an average.
*/
for (i = 0; i < aSize; i++)
{
total += randomNums[i];
if (randomNums[i] > biggest)
{
biggest = randomNums[i];
}
if (randomNums[i] < smallest)
{
smallest = randomNums[i];
}
}
average = ((float)total) / ((float)aSize);
printf("The biggest random number is %d.\n", biggest);
printf("The smallest random number is %d.\n", smallest);
printf("The average of the random numbers is %.2f.\n", average);
free(randomNums);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment