I'm trying to write a simple list. I have the next code:
#include "stdio.h"
#include "stdlib.h"
typedef struct _anObject {
void* data;
struct _anObject* previous;
struct _anObject* next;
} object_t;
typedef struct _aHead {
object_t* first;
object_t* current;
object_t* next;
object_t* last;
int index;
int size;
} head_t;
head_t* new_list(void)
{
head_t* list = malloc(sizeof(head_t));
list->first = NULL;
list->current = NULL;
list->last = NULL;
list->index = -1;
list->size = 0;
return list;
}
void add_object_to_list(head_t* list, object_t* object)
{
if (list->size == 0)
{
object->next = NULL;
object->previous = NULL;
list->first = object;
list->current = object;
list->last = object;
list->index = 0;
list->size = 1;
}
else if (list->size > 0)
{
object->previous = list->last;
object->next = NULL;
list->current->next = object;
list->current = object;
list->last = object;
list->size +=1;
list->index = list->size - 1;
}
}
object_t* createIntObject(int value)
{
int* data = &value;
object_t* object = malloc(sizeof(object_t));
object->data = data;
return object;
}
int main(int argc, char** argv)
{
head_t* list = new_list();
object_t* obj;
obj = createIntObject(22);
add_object_to_list(list, obj);
obj = createIntObject(44);
add_object_to_list(list, obj);
fprintf(stderr, "size number: %i\n", list->size);
fprintf(stderr, "First data value on the list: %i\n", *(int*) list->first->data);
fprintf(stderr, "Last data value on the list: %i\n", *(int*) list->last->data);
free(list);
free(obj);
return 0;
}
I compiled without any warning or error, but when I run the code I obtain the next and not wanted result:
size number: 2
Current data value on the list: 0
Current data value on the list: 0
What am i doing wrong? Any help will be appreciated