我试图根据下面的头(stack.h)用C来实现堆栈:通过设置指针初始化在C语言的堆叠为NULL
#ifndef STACK_H
#define STACK_H
/* An element from which stack is consisting */
typedef struct stack_node_ss {
struct stack_node_ss *next; /* pointer to next element in stack */
void *value; /* value of this element */
} stack_node_s;
/* typedef so that stack user doesn't have to worry about the actual type of
* parameter stack when using this stack implementation.
*/
typedef stack_node_s* stack_s;
/* Initializes a stack pointed by parameter stack. User calls this after he
* has created a stack_t variable but before he uses the stack.
*/
void stack_init(stack_s *stack);
/* Pushes item to a stack pointed by parameter stack. Returns 0 if succesful,
* -1 otherwise.
*/
int stack_push(void *p, stack_s *stack);
/* Pops item from a stack pointed by parameter stack. Returns pointer to
* element removed from stack if succesful, null if there is an error or
* the stack is empty.
*/
void *stack_pop(stack_s *stack);
#endif
然而,作为新带C,我停留在stack_init功能,我已经写在stack.c:
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
void stack_init(stack_s *stack) {
(*stack)->value = NULL;
(*stack)->next = NULL;
}
主程序开头:
int *tmp;
stack_s stack;
stack_init(&stack);
而这种崩溃我的程序与:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008
0x0000000100000abf in stack_init (stack=0x7fff5fbffb30) at stack.c:6
6 (*stack)->value = NULL;
你可以暗示我到正确的轨道吗?非常感谢。
这就是为什么你不会隐藏typedefs后面的指针类型,除非它真的有很好的理由。 – 2012-02-22 23:01:48
@Ed S .:完全。即使'typedef struct {...} mystruct_t;'是有问题的,恕我直言。为什么这种做法仍然在学校教授?在我看来,老师们都遭受着帕斯卡主义的终极形式的束缚。 – wildplasser 2012-02-22 23:22:02
@wildplasser:呃......当我写C时,我会''定义一个结构以避免在任何地方写'struct foo f;'。我不认为这是有问题的,但是用指针类型......有龙。 – 2012-02-23 00:09:49