【发布时间】:2012-02-22 22:56:22
【问题描述】:
我正在尝试根据以下标头(stack.h)在 C 中实现堆栈:
#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;
你能提示我正确的轨道吗?非常感谢。
【问题讨论】:
-
这就是为什么你不隐藏类型定义后面的指针类型,除非有一个真的很好的理由。
-
@Ed S.:完全正确。即使
typedef struct{... } mystruct_t;也是有问题的,恕我直言。为什么学校仍然教授这种做法?在我看来,老师们都患有帕斯卡主义的终极形式。 -
@wildplasser:嗯...当我写 C 时,我将
typedef一个结构体以避免在任何地方写struct foo f;。我不认为这是有问题的,但是对于指针类型......有龙。
标签: c null initialization linked-list