我正在嘗試使用鏈接列表實現堆棧。我的堆棧構造函數createStack()
創建一個空的(虛擬)Element
並返回一個指向該元素的雙指針(棧頂)。我的push()
方法檢查堆棧是否有虛擬元素;如果它填滿虛擬並返回,否則它爲新元素分配內存並執行必要的指針更新。奇數NULL指針行爲
我的問題是,我*stack->next
指針顯然指向NULL (0x0)
,因爲它應該,然後兩條線後,它不等於NULL (0x17)
但不知何故,通過了NULL
測試。在通話內部推動它等於(0x17)
再次,但這次它不能通過NULL
測試,因爲它應該。
所以我的問題是,這個指針到底是怎麼回事?如何/爲什麼它從(0x0)
更改爲(0x17)
,如果它等於(0x17)
它是如何通過==NULL
測試?
//main.c
int main() {
struct Element **stack;
stack = createStack();
printf("stack: %p\n", stack);
printf("*stack->next: %p\n", (*stack)->next);
if ((*stack)->next == NULL)
printf("yes the pointer is null\n");
printf("*stack->next: %p\n", (*stack)->next);
if ((*stack)->next == NULL)
printf("yes the pointer is null\n");
push (stack, 1000);
//stack.c
struct Element {
int value;
struct Element *next;
};
int push (struct Element **stack, int el) {
if ((*stack)->next == NULL) {
// first element, fill dummy element and return
printf("first value: %i !", el);
(*stack)->value = el;
return 1;
}
printf("the pointer is not null\n");
struct Element *newElement = malloc(sizeof(struct Element));
if (!newElement)
return -1;
newElement->value = el;
//add element to front of list
newElement->next = *stack;
//update pointer to new first element
*stack = newElement;
return 1;
}
struct Element** createStack() {
struct Element *dummy = malloc(sizeof(struct Element));
if (dummy == NULL)
printf("malloc failed...");
dummy->value = 99;
dummy->next = NULL;
struct Element **stack;
stack = &dummy;
return stack;
}
上面的代碼產生以下輸出:
stack: 0x7fff6c385ba8
*stack->next: 0x0
yes the pointer is null
*stack->next: 0x17
yes the pointer is null
the pointer is not null