I have a vector type defined as follows:
typedef struct vector { void **items; unsigned int capacity; unsigned int size; } vector_st; typedef vector_st *vector_t; And I allocate and free it as follows:
vector_t vector_init(unsigned int capacity) { vector_t v = (vector_t)calloc(1, sizeof(vector_st)); v->capacity = capacity; v->size = 0; v->items = malloc(sizeof(void *) * v->capacity); return v; } void vector_free(vector_t v) { if (v) { free(v->items); v->capacity = 0; v->size = 0; free(v); v = NULL; } } Now, the point is that I want to copy one vector to another one, meaning including all its content. So, I tried to define a function like this:
void vector_copy(vector_t to, vector_t from) { memcpy(to, from, sizeof(vector_st)); } But, this does not seem to work quite right, as when I do something like this:
vector_t vec = vector_init(3); vector_add(vec, 1); vector_add(vec, 2); vector_add(vec, 3); unsigned int i; for (i = 0; i < vec->size; i++) { printf("%d\n", (int)vector_get(vec, i)); } vector_t copied = vector_init(3); vector_copy(copied, vec); vector_free(vec); for (i = 0; i < copied->size; i++) { printf("%d\n", (int)vector_get(copied, i)); } For the first vector it correctly prints 1 2 3 but for the second one it prints 0 2 3. So, basically I believe it just copies maybe the memory addresses and not the actual content, as when I free the first vector the first element is set to 0. Any ideas how to copy this structure in my case?
EDIT:
void vector_resize(vector_t v, unsigned int capacity) { void **items = realloc(v->items, sizeof(void *) * capacity); if (items) { v->items = items; v->capacity = capacity; } } void vector_add(vector_t v, void *item) { if (v->capacity == v->size) { vector_resize(v, v->capacity * 2); } v->items[v->size++] = item; }
memcpy(to, from, sizeof(vector_st));What's wrong with*to = *from;?memcpy().memcpy(), and that is not the intended result. As Richard pointed out above.vector_add? Also, what do you mean by "copies the memory addresses and not the actual content"? From the code you've shown us, the only content in the vector is a collection of memory addresses.free()the object being copied, you alsofree()the copied to pointers.