通过将指针设置为NULL来初始化C中的堆栈

riz*_*ize 1 c null initialization linked-list

我正在尝试根据以下标头(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
Run Code Online (Sandbox Code Playgroud)

但是,作为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;
}
Run Code Online (Sandbox Code Playgroud)

主程序以:

  int *tmp;
  stack_s stack;
  stack_init(&stack);
Run Code Online (Sandbox Code Playgroud)

这会使我的程序崩溃:

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;
Run Code Online (Sandbox Code Playgroud)

你能暗示我走向正确的轨道吗?非常感谢.

Ker*_* SB 6

你必须为**stack自己分配内存:

*stack = malloc(sizeof(**stack));
Run Code Online (Sandbox Code Playgroud)

但请不要键入def指针类型.这真令人困惑,难以阅读.最好按值传递指针并将其留给调用者来存储指针,如下所示:

typedef struct stack_node_t
{
    struct stack_node_t * next;
    /* ... */
} stack_node;

stack_node * create_stack()
{
    stack_node * res = calloc(1, sizeof(stack_node));
    return res;
}

void destroy_stack(stack_node * s)
{
    if (!next) return;

    stack_node * next = s->next;
    free(s);
    destroy_stack(next);
}

// etc.
Run Code Online (Sandbox Code Playgroud)

然后你可以说:

stack_node * s = create_stack();

// use s

destroy_stack(s);
s = NULL;  // some people like this
Run Code Online (Sandbox Code Playgroud)