我正在嘗試編寫一個簡單的列表。我有下面的代碼:指針,列表和空白
#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;
}
我沒有任何警告或錯誤編譯,但是當我運行的代碼我獲得下一個,而不是想要的結果:
size number: 2
Current data value on the list: 0
Current data value on the list: 0
我到底做錯了什麼?任何幫助將不勝感激
投票關閉:這個問題可以通過在調試器中單步執行代碼來解決(或者至少標識)。 – 2012-01-02 22:43:46