Question: Write a C function to create an array using structures with dynamic memory allocation. The array must only hold up to integers of the amount
Write a C function to create an array using structures with dynamic memory allocation. The array must only hold up to integers of the amount (fragLength * fragNumber).
Conditions:
1. The array must allocate space dynamically for another struct.
2. In the struct, intialize fragLength and fragNumber using the parameters passed into the function.
3. You must dynamically allocate the array "fragments" to be an array of fragNumber pointers. These integer points must be initialized as null.
4. You must dynamically allocate the array "fragSizes" and initialize all its values to zero;
5. If either or both of the arguments passed to the function are 0 or negative, the function returns NULL.
Here's what I have so far:
#include
// Struct typedef struct DynamicArray { int size; // This is the amount of cells that are occupied in all the fragments or arrays int fragLength; // This is how many cells for every fragment int fragNumber; // This is the number of arrays or fragments in the struct int allocatedFragments; // This is the number of allocated fragments, or fragments not set to NULL int *fragSizes; //This stores the quantity of cells used in every fragment int **fragments; // This is an array of pointers to each fragment } DynamicArray;
// Declaring the function DynamicArray *createDynamicArray(int fragNumber, int fragLength);
// Main void main(){
createDynamicArray();
}
// Function DynamicArray *createDynamicArray(int fragNumber, int fragLength) { struct DynamicArray *ptr;
// Making variables for passed in arguments int fragNumberStruct = fragNumber; int fragLengthStruct = fragLength; int i; int fragments[50]; ptr = (struct DynamicArray *)malloc(fragNumberStruct * sizeof(struct DynamicArray));
// Setting all the pointers to null for(i=0;i if(fragNumberStruct==NULL||fragLengthStruct==NULL){ return NULL; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
