89 lines
2.3 KiB
C
Executable File
89 lines
2.3 KiB
C
Executable File
/*
|
|
In this task, you should get familiar with malloc() and free().
|
|
In addition, you should implement the functions
|
|
- fillArray(int size, int base_number)
|
|
- printArray(int* numbers, int size).
|
|
|
|
main:
|
|
- user can enter the size of the integer array
|
|
- user can enter the base number that is used to fill the array
|
|
- print "Memory allocation failed\n" if memory allocation in fillArray failed
|
|
- immediately return exit code 1
|
|
- free the allocated memory using free() at the end.
|
|
|
|
call createAndFillArray(int size, int base_number)
|
|
- create array by allocating enough memory for it on the heap using malloc()
|
|
- if memory allocation is not successful, return NULL
|
|
- After allocating fill the array with integer values
|
|
with multiples of base_number using pointer arithmetic
|
|
- Return pointer to array at the end of the function
|
|
|
|
call printArray(int* numbers, int size)
|
|
- print the array using pointer arithmetic
|
|
|
|
Examples:
|
|
|
|
Size: 5
|
|
Fill numbers array with multiples of: 3
|
|
3 6 9 12 15
|
|
|
|
Size: 4
|
|
Fill numbers array with multiples of: 5
|
|
5 10 15 20
|
|
|
|
Size: 12
|
|
Fill numbers array with multiples of: 100
|
|
100 200 300 400 500 600 700 800 900 1000 1100 1200
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h> // TODO: Include the required header file
|
|
|
|
int* createAndFillArray(int size, int base_number)
|
|
{
|
|
// TODO: Allocate memory
|
|
int *numbers = (int*) malloc( size * sizeof(int) );
|
|
// TODO: Check if memory could be allocated
|
|
if ( numbers == NULL ) return NULL;
|
|
|
|
// TODO: Fill the array with multiples of base_number using pointer arithmetic and return it
|
|
for ( int position = 0 ; position < size; position++ )
|
|
{
|
|
*(numbers + position) = base_number * ( position + 1 );
|
|
}
|
|
|
|
return numbers;
|
|
}
|
|
|
|
void printArray(int* numbers, int size)
|
|
{
|
|
for (int position = 0; position < size; position++)
|
|
{
|
|
printf("%d ", *(numbers + position));
|
|
}
|
|
// TODO: Print the array using pointer arithmetic
|
|
}
|
|
|
|
int main(void)
|
|
{
|
|
int size = 0;
|
|
printf("Size: ");
|
|
scanf("%d", &size);
|
|
|
|
int base_number = 0;
|
|
printf("Fill numbers array with multiples of: ");
|
|
scanf("%d", &base_number);
|
|
|
|
int* numbers = createAndFillArray(size, base_number);
|
|
if ( numbers == NULL )
|
|
{
|
|
printf("Memory allocation failed\n");
|
|
return 1; // TODO: Return 1 if the memory allocation was not successful
|
|
}
|
|
|
|
printArray(numbers, size);
|
|
|
|
free(numbers); // TODO: Free the allocated memory
|
|
|
|
return 0;
|
|
} |