Create a single main function that does the following (all arrays should be dyna
ID: 3544862 • Letter: C
Question
- Create a single main function that does the following (all arrays should be dynamic, not static):
- Creates an integer array of size 10
- Using square bracket notation, fill the array with the following values (in order):
-
- 100, 90, 80, ..., 10
- Print all of the values from the array to verify that they were set properly using square bracket notation
- Using the same variable, make another integer array of size 5 (not reallocated).
- Fill this array with the following values using pointer arithmetic (not square bracket notation)
-
- 0, -5, 5, 10, -10
- Print all of the values from the array using pointer arithmetic
- Clean up any memory that needs to be freed
Explanation / Answer
#include<stdio.h>
#include<malloc.h>
int main()
{
int i;
int * arr;
//allocating space for an array of size 10
arr = malloc(10*sizeof(int));
//initializing the array using bracket notation
for(i=0;i<10;i++)
arr[i]=(10-i)*10;
//printing the array using bracket notation
for(i=0;i<10;i++)
printf("%d ",arr[i]);
//initializing the array using pointer arithmetic
*(arr+0) = 0;
*(arr+1) = -5;
*(arr+2) = 5;
*(arr+3) = 10;
*(arr+4) = -10;
//printing the array using pointer arithmetic
for(i=0;i<5;i++)
printf("%d ",*(arr+i));
//freeing the allocated memory
free(arr);
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.