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

I need help with the following program in C programming. Resize Array An actual

ID: 3601969 • Letter: I

Question

I need help with the following program in C programming.

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 to 0x7fe766500000):

array[0] = 84

array[1] = 53

array[2] = 25

array[3] = 92

array[4] = 51

Enter New Size: 3

array (pointing to 0x7fe766600000):

array[0] = 84

array[1] = 53

array[2] = 25

Explanation / Answer

#include <stdio.h>

#include <stdlib.h>

void resize_array(int ** array, int size, int new_size) {

int *temp;

temp = realloc(**array, new_size*sizeof(*temp));

if (!temp) {

free(**array);

return 0;

}

**array = temp;

free(temp);

return new_size;

}

int main() {

int *arr;

int size,i;

printf("Enter size: ");

scanf("%d",&size);

arr = (int*)malloc(size*sizeof(*arr));

printf("array (pointing to %p",arr);

srand(time(NULL));

int val = rand() % 100;

/* filling array values */

for(i=0;i<size;i++) {

val = rand() % 10;

arr[i] = val;

}

/* printing array values */

for(i=0;i<size;i++) {

printf(" array[%d] = %d",i,arr[i]);

}

//reading new size

printf("Enter New Size: ");

int new_size;

scanf("%d",&new_size);

resize_array(arr,size,new_size);

printf("array (pointing to %p",arr);

/* printing array values */

for(i=0;i<size;i++) {

printf(" array[%d] = %d",i,arr[i]);

}

return 0;

}