88.7k views
0 votes
Consider you want to dynamically allocate memory for an array of arrays, where each array has variable length. The type of the arrays would be float. Write a function that takes two items: i) an integer P that represents number of arrays, and ii) An array called Lengths of size P that contains Lengths for P number of arrays. After allocating memory for the arrays, the function should fill-up the arrays with random numbers from 1 to 100 (you can put an int to a float variable. The integer will get promoted to float automatically). At the end the function returns appropriate pointer. Next write a set of statements to show how you would free-up the memory.

User Thnee
by
4.5k points

1 Answer

5 votes

Answer: provided in the explanation segment

Step-by-step explanation:

below is the code to run this program...cheers i hope this helps!!!

a. float **AllocateArrayOfArrays(int P, int *Length)

{

float **arr = (float **)malloc(P * sizeof(float *));

for(i=0; i< P; i++)

arr[i] = (float *)malloc(Lengths[i] * sizeof(float));

for(i =0; i<P;i++)

for(j=0;j<Lengths[i];j++)

arr[i][j] = rand() % 100 + 1;

return arr;

}

To free the allocated memory:

void destroyArray(float** arr)

{

free(*arr);

free(arr);

}

b.

float **arrayFloat; //array of arrays variable to hold the float values

int rowlength, int colLenArr[rowlength];

arrayFloat = AllocateArrayOfArrays(rowlength, colLenArr);

The complete code is:

#include <stdio.h>

#include <stdlib.h>

float **AllocateArrayOfArrays(int P, int *Lengths)

{

int i, j;

float **arr = (float **)malloc(P * sizeof(float *));

for(i=0; i< P; i++)

arr[i] = (float *)malloc(Lengths[i] * sizeof(float));

for(i =0; i<P;i++)

for(j=0;j<Lengths[i];j++)

arr[i][j] = rand() % 100 + 1;

return arr;

}

//To free the allocated memory:

void destroyArray(float** arr)

{

free(*arr);

free(arr);

}

int main()

{

int i,j;

float **arrayFloat; //array of arrays variable to hold the float values

int rowlength,colLenArr[rowlength];

rowlength = 3;

for(i=0; i<3;i++)

colLenArr[i] = i+1;

arrayFloat = AllocateArrayOfArrays(rowlength, colLenArr);

for(i =0; i<rowlength;i++)

{

for(j=0;j<colLenArr[i];j++)

printf("%f ", arrayFloat[i][j]);

printf("\\");

}

destroyArray(arrayFloat);

}

i hope this was helpful

User Chris Wijaya
by
5.2k points