【发布时间】:2021-09-01 15:11:49
【问题描述】:
我的代码不起作用,但是当我将 struct stack *sp; 更改为 struct stack * sp = (struct stack *) malloc(sizeof(struct stack)); 时,它开始工作。我对何时将堆中的内存分配给struct stack *ptr 以及何时不分配感到困惑。如果你能给我一个例子更好,什么时候可以使用struct stack *ptr,什么时候可以使用struct stack * sp = (struct stack *) malloc(sizeof(struct stack));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
int size;
int top;
char *arr;
};
int stackTop(struct stack* sp){
return sp->arr[sp->top];
}
int isEmpty(struct stack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size - 1)
{
return 1;
}
else
{
return 0;
}
}
void push(struct stack* ptr, char val){
if(isFull(ptr)){
printf("Stack Overflow! Cannot push %d to the stack\n", val);
}
else{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack* ptr){
if(isEmpty(ptr)){
printf("Stack Underflow! Cannot pop from the stack\n");
return -1;
}
else{
char val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
int precedence(char ch){
if(ch == '*' || ch=='/')
return 3;
else if(ch == '+' || ch=='-')
return 2;
else
return 0;
}
int isOperator(char ch){
if(ch=='+' || ch=='-' ||ch=='*' || ch=='/')
return 1;
else
return 0;
}
char* infixToPostfix(char* infix){
struct stack *sp;
sp->size = 10;
sp->top = -1;
sp->arr = (char *) malloc(sp->size * sizeof(char));
char * postfix = (char *) malloc((strlen(infix)+1) * sizeof(char));
int i=0; // Track infix traversal
int j = 0; // Track postfix addition
while (infix[i]!='\0')
{
if(!isOperator(infix[i])){
postfix[j] = infix[i];
j++;
i++;
}
else{
if(precedence(infix[i])> precedence(stackTop(sp))){
push(sp, infix[i]);
i++;
}
else{
postfix[j] = pop(sp);
j++;
}
}
}
while (!isEmpty(sp))
{
postfix[j] = pop(sp);
j++;
}
postfix[j] = '\0';
return postfix;
}
int main()
{
char * infix = "x-y/z-k*d";
printf("postfix is %s", infixToPostfix(infix));
return 0;
}
【问题讨论】:
-
在任何情况下都不应使用
struct stack * sp = (struct stack *) malloc(sizeof(struct stack));。 c - Do I cast the result of malloc? - Stack Overflow -
struct stack *ptr;只是声明了一个指针。如果你想取消引用ptr,你必须稍后分配一个有效的指针。 -
当您取消引用未初始化的指针时,由于尝试写入(或读取)到无效位置的分段错误,您的程序很有可能被终止。在尝试打印任何内容之前,您的程序中会发生这种无效的取消引用。
-
当我没有为堆中的 struct stack *sp 分配内存时,代码没有给出输出,但是当我为其分配内存时,它开始给出正确的输出。就像在这个函数中一样,我没有为 struct stack *sp 分配内存,但它正在工作。
int parenthesisbalance(char *exp) {struct stack *sp;sp->size = 100;sp->top = -1; sp->arr(char*)malloc(sp>size*sizeof(char)); for (int i = 0; exp[i]!= '\0'; i++) {if (exp[i]=='('){push(sp,'(');} else if (exp[i]==')') {if (isempty(sp)){return 0;} else{pop(sp);}}} if (isempty(sp)){return 1;}else{return 0;}} -
未定义的行为在取消引用未初始化的指针时被调用。它可以导致任何结果并且不需要崩溃。
标签: c pointers memory struct heap-memory