簡體   English   中英

將指針傳遞給struct並將int傳遞給C中的函數以實現堆棧

[英]Pass a pointer to struct and a int to a function in C to implement a stack

我正在嘗試在C中實現堆棧。我僅實現了將包含一個數組的結構,該結構當前僅包含該數組的大小以及添加到堆棧中的最后一項的位置

這是部分實現,給我帶來了麻煩。

在stack.h中

#include <stdlib.h>
#include <stdbool.h>

typedef struct Stack
{
    int max_size;
    int top;
    // int *contents;
} Stack;

Stack *stack_create(int n);
bool stack_is_empty(Stack *stack);
bool stack_is_full(Stack *stack);
void stack_push(Stack *stack, int value);

在stack.c中:

#include <stdio.h>
#ifndef STACK_H
#include "stack.h"
#endif

Stack *stack_create(int n)
{
    Stack stack;
    Stack *s = &stack;
    s->max_size = n;
    s->top = 0;
    // s->contents = (int *)malloc(sizeof(int) * n);
    return s;
}


bool stack_is_empty(Stack *stack)
{
    if (stack->top == 0)
    {
        return true;
    }
    return false;
}

bool stack_is_full(Stack *stack)
{
    if (stack->top == stack->max_size)
    {
         return true;
    }
    return false;
} 

void stack_push(Stack *stack, int value)
{

     if (!stack_is_full(stack))
     {
          printf("max_size: %d\n", stack->max_size);
          printf("top: %d (%p)\n", stack->top++, &stack->top);
          printf("value: %d (%p)\n", value, &value);
     }
     else
     {
          printf("Can't push. max_size==%d reached.\n", stack- >max_size);
          exit(EXIT_FAILURE);
     }
}

在main.c中:

 #include <stdio.h>
 #include <stdlib.h>
 #include "stack.h"

 #define SIZE 3

 int main()
 {
     Stack *s = stack_create(SIZE);
     printf("stack_is_empty: %d\n", stack_is_empty(s));
     stack_push(s, 100);
     printf("stack_is_empty: %d\n", stack_is_empty(s));
     stack_push(s, 30);
     printf("stack_is_empty: %d\n", stack_is_empty(s));
     stack_push(s, 20);
     printf("stack_is_empty: %d\n", stack_is_empty(s));

     return 0;
 }

main產生以下輸出:

stack_is_empty: 1
max_size: 3
top: 100 (0x7ffd5430dfb4)
value: 101 (0x7ffd5430dfb4)
stack_is_empty: 0
max_size: 3
top: 30 (0x7ffd5430dfb4)
value: 31 (0x7ffd5430dfb4)
stack_is_empty: 0
max_size: 3
top: 20 (0x7ffd5430dfb4)
value: 21 (0x7ffd5430dfb4)
stack_is_empty: 0

為什么value的地址與stack->top相同?

問題1:您正在stack_create函數中為堆棧本地分配內存。 一旦功能超出范圍,內存將被釋放。 因此,您將有一個懸空的指針。

問題2:您只為一個實例分配內存,而不考慮'n'的值

typedef struct Stack
{
    int max_size;
    int *contents;
    int top;
    // int *contents;
} Stack;

Stack *stack_create(int n) {
    Stack *s;
    s = (Stack *)malloc(sizeof(Stack));
    s->contents = (int *)malloc(sizeof(int) * n);
    s->max_size = n;
    s->top = 0;
    return s;
}

暫無
暫無

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

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