我正在尝试使用链接列表实现堆栈。我的堆栈构造函数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