Good morning,
I am learning to work with C pointers and I have a question about an algorithm that I am implementing that makes extensive use of malloc
, realloc
and free
, this is the code:
List.h
#ifndef _LIST_H_
#define _LIST_H_
typedef struct {
int Count;
void **Elements;
} List;
List *list_new();
void list_insert(List *l, void *elem);
void *list_getelem(List *l, int offset);
void list_removeoffset(List *l, int elem);
void list_free(List *l);
int list_get_count(List *l);
#endif
List.c
#include <stdio.h>
#include <stdlib.h>
#include "List.h"
List *list_new() {
List *ptr = malloc(sizeof(List));
ptr->Elements = malloc(sizeof(void*));
ptr->Count = 0;
return (ptr) ? ptr : NULL;
}
void list_insert(List *l, void *elem) {
if (l->Count == 0)
l->Elements = realloc(l->Elements, sizeof(void*));
else
l->Elements = realloc(l->Elements, (sizeof(void*) * l->Count));
l->Elements[l->Count] = elem;
l->Count++;
}
void *list_getelem(List *l, int offset) {
if (offset < 0 || offset >= l->Count) return NULL;
return l->Elements[offset];
}
void list_removeoffset(List *l, int elem) {
if (elem < 0 || elem >= l->Count) return;
l->Elements[elem] = NULL;
l->Count--;
l->Elements = realloc(l->Elements, sizeof(void*) * l->Count);
}
void list_free(List *l) {
if (l) {
free(l->Elements); free(l);
}
}
int list_get_count(List *l) {
return l->Count;
}
My problem arises within the declaration of the method list_removeoffset(...)
I can not eliminate an element in a position offset
in the array of pointers.
main()
:
List *MyList = list_new();
list_insert(MyList, (int*)3416); printf("List Count Now: %d\n", list_get_count(MyList));
list_insert(MyList, (char*)"hello world"); printf("List Count Now: %d\n", list_get_count(MyList));
list_insert(MyList, (int*)5); printf("List Count Now: %d\n", list_get_count(MyList));
This is the result I get with the previous code:
List Count Now: 1
List Count Now: 2
List Count Now: 3
Element at position 1: hello world
Effectively it works, but when trying with the following code to remove the elements:
list_removeoffset(MyList, 1); // Intento remover el elemento en la posicion 1.
It seems to be deleted, but in the same way it frees the memory of the other elements that are after it and shows me as a result 0
.
How can I delete or release only one element and not all of the elements that are starting from this?