The goal of this problem is to perform operations on an array, without using the
ID: 3770171 • Letter: T
Question
The goal of this problem is to perform operations on an array, without using the “subscript operator”, but just with pointers.
Step 1:
Inside the main function, crate an array of 20 elements, and initialize it with unique random elements. Print the array.
Step 2:
*Write a function “int* ArrayManipulator(int* arrayPoiner, const int size)” . This function receives a pointer to the array created in Step 1.
* Further, inside ArrayManipulator create a new array “ReversedArray” and dynamically allocate memory to this array using new operator with length as “size”.
* Initialize “ReversedArray” with the elements pointed by the arrayPoiner.
* Now, reverse the elements of “ReversedArray” strictly using pointers, you cannot use
subscript operator.
* Return the pointer to “ReversedArray”
Step 3:
Inside the main function, receive the pointer returned in step 2. Print the elements of “ReversedArray” just using the received pointer.
Example:
The initial array elements are: 45, 25, 78, 32, 56, 74, 89, 22
Inside ArrayManipulator
The elements of ReversedArray: 45, 25, 78, 32, 56, 74, 89, 22
Inside main:
The elements of ReversedArray: 22, 89, 74, 56, 32, 78, 25, 45
Explanation / Answer
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define MAX 20
int* ArrayManipulator(int* arrayPointer,const int size)
{
int temp,i;
int *ReversedArray = new int[size];
for(i=0;i<size;i++)
*(ReversedArray+i) = *(arrayPointer+i);
printf("Inside ArrayManipulator ");
printf("The elements od ReversedArray: ");
for(i=0;i<size;i++)
printf("%d ",*(ReversedArray+i));
for(i=0;i<size/2;i++)
{
temp = *(ReversedArray+i);
*(ReversedArray+i) = *(ReversedArray+size-i-1);
*(ReversedArray+size-i-1) = temp;
}
return ReversedArray;
}
int main()
{
srand(time(NULL));
int *data = new int[MAX];
int *ReversedArray;
int i;
for(i=0;i<MAX;i++)
data[i] = rand()%100+1;
printf("The initial array elements are: ");
for(i=0;i<MAX;i++)
printf("%d ",*(data+i));
ReversedArray = ArrayManipulator(data,MAX);
printf("Inside main ");
printf("The elements od ReversedArray: ");
for(i=0;i<MAX;i++)
printf("%d ",*(ReversedArray+i));
delete data;
delete ReversedArray;
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.