Home > Software design >  Create a dynamic C array for different structures
Create a dynamic C array for different structures

Time:11-27

Is it possible to create a dynamic C array which works for all types. In this instance the dynamicArr would have to work for both struct1 and struct. What should the type of structuretype be to work for both struct1 and struct2 depending on the user initialization?

typedef struct dynamicArr
{
    structuretype *arr;
    int capacity;
    int size;
}dynamicArr;

typedef struct struct1
{
    int id;
    char *field1;
    char *field2;
    int num;
}struct1;
typedef struct struct2
{
    char *field;
    int num1;
    int num2;
}struct2;

CodePudding user response:

typedef struct { 
   void *dataStructure; 
   int size; 
   int numElements; 
} dynamicArray; 
 
dynamicArray *init(int initialSize); 
 
void push(dynamicArray *A, void *element); 
 
void *pop(dynamicArray *A); 
 
void setElement(dynamicArray *A, int position, void *element); 
 
void *getElement(dynamicArray *A, int position); 

You could probably add more functions to the list. Each would be responsible for resizing the array if the number of elements were to exceed the existing size of the array. Your external program would be responsible for casting each data element into a pointer of the data type you wished to use and vice versa.

CodePudding user response:

Making the structuretype void* should work although dangerous since you wouldn't have any way of knowing which type your pointer originally pointed to.

I would recommend adding some enum field to the dynamic array struct which would remember the original type of the data it's holding giving you the ability to cast it back "safely" when needed.

CodePudding user response:

You could use void* (or an arry of void*). Be ware that you will loose any information about what the pointer is you are storing though.

A void-pointer will accept a pointer of any type without warning. malloc() for example returns void*, since you may want to use it for char*, int*, etc.

Storing objects in void* is very dangerous (especially if you plan to use multiple types) and should only be done with extreme caution, since, for example, this would compile without even a warning:

#include <stdint.h>
#include <stdio.h>

int main() {
    uint8_t number = 42;
    void* ptr = &number;
    uint32_t* new_number = ptr;

    printf("%i\n", *new_number);
}

This case can lead to serious memory corruption and thus may result in crashes and security issues.

  • Related