Reputation: 13257
I am writing a dynamic array in C.
typedef struct __c_array {
void**_elem;
int cur_size;
int capacity;
}c_array;
My Interface look like this:
extern void push_back_c_array ( c_array*, void *);
Now user will have to allocate memory for the element to be pushed into the array . Is there any way to avoid this using void *.
I want use this to do following
int a = 5;
push_back_c_array ( <ARRAY_PTR>, a );
Is this possible.
Upvotes: 2
Views: 287
Reputation: 10457
you example whit a=5 should work as long as you will use integers or any other type that has same size as int. User of generic array will want to push structs, just like your. But, big elements can not/should not should not be passed by value, but its pointer should be passed.
using generic and no being bounded on sizeof(int) bring some extra effort from user. I think that best solution is that you pass allocated pointer (void*) in function and whoever wants to take this element out, should free() this struct.
Upvotes: 0
Reputation: 8292
It is possible, if you provide a version of push_back_c_array() that will copy the value provided. For this you'll need an extra argument, that specifies the size of the value:
push_back_c_array(c_array* arr, void* val, unsigned int size);
You allocate memory in heap for the new value and then do memcpy. But after that you'll need to deallocate it back. So, you'll need to remember, which values are allocated by you, and which ones - by the caller. Rather nasty... So, if you do that - do that always, and describe this convention in the documenation to your function.
Upvotes: 2
Reputation: 7282
Your example array holds items of type (void*). It holds pointers. You seem to be wanting it to hold arbitrary types. In this case and int. Do you want to store copies of inserted data or to simply store pointers given to you by the caller?
A while ago I wanted simple array like behavour for a game I was writing and came up with xrlist. A while later I wanted to store them and randomly access them so came up with xrhash.
xrlist and xrhash store user supplied pointers and expect all elements to be of the same type (xrhash has a hashcode and comparison callback function )
Upvotes: 0
Reputation: 10381
You might be better served allocating a small chunk of memory (perhaps to hold unions) in the beginning, and pushing back elements until you fill it up. Then either realloc, or allocate an array twice the size and copy everything over.
Upvotes: 0