Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Resize Array An actual array cannot be resized. However, a dynamically allocated

ID: 3603391 • Letter: R

Question

Resize Array An actual array cannot be resized. However, a dynamically allocated array could seem to be resized by creating a new array and copying the elements from the original array into the new array. Your task is to write a function to "resize" an array of integers. Write a program to get an array size from the user and dynamically allocate an array of that size and fill it with random integers less than 100 and print the array. Then, get a new size from the user and use the resize function and print the array. Here's a function header to get you started void resize_array(int array, int size, int new size) Sample Runs Enter Size: 3 array (pointing to 0x7fd15fd00000): array [0] 37 array[1] = 65 array [ 2 ] -44 Enter New Size: !5 array (pointing to 0x7fd15fd00010) array [0] 37 array[1] = 65 array [2] 44 array [3] 0 array [ 4 ] 0 Enter Size: 5 array (pointing array [0] 84 array[1] 53 array [2] 25 array [3] 92 array [4] 51 to 0x7fe766500000): Enter New Size: 3 array (pointing to 0x7fe766600000): array [0] 84 array[153 array [2] 25

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>

void resize_array(int **array, int size, int new_size) {
  
int *new_array = (int *) malloc(new_size*sizeof(int));
int i;
for(i = 0; i < size; i++) {
new_array[i] = (*array)[i];
}
free(*array);
*array = new_array;
}

int main()
{
int size;
printf("Enter Size: ");
scanf("%d", &size);
  
int *array = (int *)malloc(size*sizeof(int));
  
int i;
for (i = 0; i < size; i++) {
array[i] = rand() % 100 + 1;
}
  
printf("array (pointing to %p): ", array);
for (i = 0; i < size; i++) {
printf("array[%d] = %d ", i, array[i]);
}
  
printf(" ");
int new_size;
printf("Enter New Size: ");
scanf("%d", &new_size);
resize_array(&array, size, new_size);
  
printf("array (pointing to %p): ", array);
for (i = 0; i < new_size; i++) {
printf("array[%d] = %d ", i, array[i]);
}

return 0;
}

Sample run

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote