a) In the main function, define an integer array with five entries and assign va
ID: 3794113 • Letter: A
Question
a) In the main function, define an integer array with five entries and assign values to the entries. Display the entries in the order in which they occur within the array. b) Pass the array to a function. Within the function, dynamically allocate a new integer array. Programmatically assign the value from the original array to the new array in reverse order such that the first entry in the original array becomes the fifth entry in the new array, the second entry in the original array becomes the fourth entry in the new array, and so on. Display the contents of the new array in the function. Do not return the new array from the function. Do not change the contents of the original array. Use a pointer to an array, i.e., use dereferencing, when assigning and displaying the contents of the new array. The dynamically allocated array will be deleted.
Explanation / Answer
Here is the solution:
#include <stdio.h>
#include <stdlib.h>
void reverse_array(int array[] );
int main()
{ int i;
int array[5]={10,20,30,40,50};
printf("Original array : ");
for(i=0;i<5;i++){
printf("%d ",array[i] );
}
reverse_array(array);
return 0;
}
void reverse_array(int array[])
{
int *s, c, d,k,n=5,i;
s = (int*)malloc(sizeof(int)*n);
if( s == NULL ){
exit(0);
}
for (c = n - 1, d = 0; c >= 0; c--, d++){
*(s+d) = array[c];
}
printf("new array : ");
for ( c = 0 ; c < n ; c++ )
printf( "%d ",*(s+c));
free(s);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.