gpt4 book ai didi

c - postfix 计算器遇到段错误问题

转载 作者:行者123 更新时间:2023-11-30 15:20:23 24 4
gpt4 key购买 nike

我正在尝试使用链接列表创建一个后缀计算器。当我编译时,它不会显示任何错误,但当它执行时,它会显示段错误。我不知道如何处理这个问题,请帮忙。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct node {
int num;
struct node *next;
} node;

void push(int num, node **head);
int pop(node **head);
void display(node **head);
int is_empty();
int evaluatePostfix();

struct node *head;

int main() {
head = NULL;
char exp[1000]; // = "5 1 2 + 4 * + 3 -";
printf("Input expression:\t");
fgets(exp, 1000, stdin);
for(int i = 1; i <= strlen(exp); i++) {
if(exp[i] == '\n') {
exp[i] = '\0';
}
else if (exp[0] == '\n') {
printf("stack is empty\n");
exit(0);
}
}
printf("%s = %d\n", exp, evaluatePostfix(exp));

return 0;

}

int evaluatePostfix(char* exp)  {
char * token;
int counter = 0;
char temp[256][256];
token = strtok(exp, " ");
while(token != NULL) {
strcpy(temp[counter], token);
counter++;
token = strtok(NULL, " ");
}

for (int i = 0; temp[i]; ++i) {
if (isdigit(*(temp[i]))) {
int val = atoi(temp[i]);
push(val, &head);
}
else {
int val1 = pop(&head);
int val2 = pop(&head);
switch (exp[i]) {
case '+': push(val2 + val1, &head);
printf("%d\n", (*head).num);
break;
case '-': push(val2 - val1, &head); break;
case '*': push(val2 * val1, &head); break;
case '/': push(val1 / val2, &head); break;
}
}
}
return pop(&head);
}


void push (int item, node **head) {
node *temp;
node * get_node(int);
temp = get_node(item);
temp->next = *head;
*head = temp;
}

node *get_node(int item) {
node *temp;
temp = (node*)malloc(sizeof(node));
if (temp == NULL)
printf("\nMemory cannot be allocated");
temp->num = item;
temp->next = NULL;
return(temp);
}


int pop(node **head) {
int item;
node *temp;
item = (*head)->num;
temp = *head;
*head = (*head)->next;
free(temp);
return(item);
}

int is_empty(node *temp) {
if (temp == NULL)
return 1;
else
return 0;
}


void display(node **head) {
node *temp;
temp = *head;
if(head == NULL) {
printf("stack is empty\n");
return;
}
printf("\n");
printf("=========\n");
while(temp!=NULL) {
printf("%d\n", (*temp).num);
temp = (*temp).next;
}
printf("=========\n");
}

最佳答案

鉴于此声明...

char temp[256][256];

...这里的循环终止条件是错误的:

for (int i = 0; temp[i]; ++i)   {

C 多维数组不是数组引用的 Java 风格数组。它们是实际数组的数组。当 i 超过已写入数据的 temp[] 元素数量时,表达式 temp[i] 不会为 false。

看起来你想要的很简单

for (int i = 0; i < counter; ++i)   {

。或者,在开始计算之前没有特别需要进行标记化。您可以轻松地将函数 evaluatePostfix() 中的两个循环合并为一个。这会更简单一些,并且会消除表达式中项数的任何固定限制。

更新:可能如下所示:

for (token = strtok(exp, " "); token; token = strtok(NULL, " ")) {

/* ... use token instead of temp[i] ... */

}

可以想象,您的代码中还存在其他错误,尽管我在扫描时没有发现任何错误。

关于c - postfix 计算器遇到段错误问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com