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

Make sure to program in C 1. Write a function create_array with the following pr

ID: 3694572 • Letter: M

Question

Make sure to program in C

1. Write a function create_array with the following prototype:

int * create_array (int n, int initial_value);

The function should return a pointer to a dynamically allocated array of integer values, with n elements, each of which is initialized to initial_value. The function should print an error message and return NULL if the array cannot be allocated.

2. Write a program that uses the above function as follows:

The program asks the user to enter the size of the array and the initial values.

The program then calls the create_array function to create the new array. The program should exit with an error code if the function fails to allocate the array.

Once the array is created, the program should save the array in a binary file called “arrayb.dat”.

3. Check the contents of your binary file with the xxd binary file viewer:

            >xxd –b –c 4 arrayb.dat

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>
int * create_array (int n, int initial_value)
{
int *arr = (int *)malloc(sizeof(int)*n);
int i;
for(i=0;i<n;i++)arr[i]=initial_value;
return arr;
}
int main()
{
int size,val,i;
printf("Enter the size of the array:");
scanf("%d",&size);
printf("Enter the initial value of the array:");
scanf("%d",&val);
int * arr = create_array(size,val);
FILE *fp = fopen("arrayb.dat","w");
for(i=0;i<size;i++)
{
fprintf(fp,"%d ",arr[i]);
}
return 0;
}

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