簡體   English   中英

通過將指針設置為NULL來初始化C中的堆棧

[英]Initialize a stack in C by setting pointer to NULL

我正在嘗試根據以下標頭(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;

你能提示我正確的方向嗎? 非常感謝。

您必須為**stack本身分配內存:

*stack = malloc(sizeof(**stack));

但是請不要使用typedef指針類型。 這確實令人困惑並且難以閱讀。 最好按值傳遞指針,然后將其留給調用方以存儲指針,如下所示:

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.

然后,您可以說:

stack_node * s = create_stack();

// use s

destroy_stack(s);
s = NULL;  // some people like this

您正在取消引用未初始化的指針,從而導致未定義的行為。

因為此函數正在創建一個新的堆棧,所以您需要為該堆棧分配一些動態內存,然后將指針設置為指向該新分配的內存:

void stack_init(stack_s *stack) {
    *stack = malloc(sizeof(**stack)); // create memory for the stack

    (*stack)->value = NULL;
    (*stack)->next = NULL;
}

stack_s stack;
stack_init(&stack);

然后,您應該具有一個稱為stack_destroy的函數,該函數將free動態內存並將指針設置為NULL

void stack_destroy(stack_s *stack) {
    free(*stack);
    *stack = NULL;
}

您應該將堆棧初始化為NULL-不要向其推送NULL值:

void stack_init(stack_s *stack) {
    *stack=NULL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM