我試圖根據下面的頭(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