C — 如何使我的堆栈完全动态化?

标签 c stack malloc push realloc

目前我的代码使用堆栈并将用户输入的字符串一一插入堆栈。但是我想让它变得动态,我会 malloc/realloc 吗?我知道我错过了一些完全明显的东西,但我想我视野狭隘……帮忙?

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
char a [MAXSIZE];
char * p = a;
int top = -1;

void push ( char n )
{
    if ( top == 99)
    {
        printf( "stack overflow");
        return;
    }
    top+=1;
    a[top] = n;
}


/*  Function to delete an element from the stack */
void pop(){
    if(top == -1)
        printf("Stack is Empty");
    else
        top-=1;

}

char *inputString(FILE* fp, size_t size){
    //The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(char)*len);
}
int balanced (char * m){
    int size = sizeof(m);
    int i, j;
    for (i=0; i<=size; ++i){
        push(m[i]);
    }
}
int main(void){
    char *m;

    printf("input string : ");
    m = inputString(stdin, 10);
    printf("%s\n", m);
    balanced(m);
    int i;
    for (i=0;i<=sizeof(a);++i){
        printf("\n%c", a[i]);
    }
    free(m);
    return 0;
}

最佳答案

如果我正确理解你的问题,这就是你应该做的。

struct Stack
{
    char c;
    struct Stack *next;
}*stack = NULL;

char pop()
{
    if(stack == NULL)
    {
        printf("Stack Underflow\n");
        return NULL;
    }
    c = stack -> c;
    struct Stack * temp = stack;
    stack = stack -> next;
    free(temp);

    return c;
}

void push(char c)
{
    struct Stack * temp = malloc(sizeof(struct Stack));
    temp -> next = NULL;
    temp -> c = c;

    if (stack == NULL)
        stack = temp;
    else
    {
        temp -> next = stack;
        stack = temp;
    }
}

关于C — 如何使我的堆栈完全动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29483064/

相关文章:

c - linux sparc so 库中的名称重整

c - 在c中实现 union 比较的实用方法

c++ - 如何在 C++ 中创建一个位于堆而不是堆栈的数组?

c++ - 我的链表节点删除功能导致程序的其他部分崩溃

c - 在 C 中将 free 与二维数组一起使用时出错

C使用函数参数返回值

c - 当这些符号是 glibc 的一部分时,链接器会更改这些符号名称

c++ - 使用栈来存储对象

c - 如何在 C 中动态分配结构?

c - 为什么用 malloc 初始化的指针是空指针?