c - C中指针和整数的比较
问题描述
我想要编程的是让用户输入一系列括号/大括号并评估它们是否正确嵌套。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define STACK_SIZE 100
char contents[STACK_SIZE];
int top = 0;
void make_empty(void)
{
top = 0;
}
bool is_empty(void)
{
return top == 0;
}
bool is_full(void)
{
return top == STACK_SIZE;
}
void push(char i)
{
if(is_full())
stack_overflow();
else
contents[top++] = i;
}
char pop(void)
{
if(is_empty())
stack_underflow();
else
return contents[--top];
}
void stack_overflow(void)
{
printf("Stack overflow\n");
exit(EXIT_FAILURE);
}
void stack_underflow(void)
{
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
int main(void)
{
char ch;
printf("Enter parentheses and/or braces: ");
while((ch = getchar()) != '\n')
{
if(ch == '(' || ch == '{')
push(ch);
else if(ch == ')')
{
if(pop != '(') /// compiler says it is a comparison between pointer and integer.
{
printf("not nested properly!");
exit(EXIT_FAILURE);
}
}
else if(ch == '}'){
if(pop != '{') /// compiler says it is a comparison between pointer and integer.
{
printf("not nested properly!");
exit(EXIT_FAILURE);
}
}
}
if(is_empty())
printf("Parentheses/braces are nested properly");
else
printf("not nested properly!!");
/* if the stack is empty, it is nested properly, otherwise not.*/
return 0;
}
编译器说pop和'('或'{'之间的比较是指针和整数之间的比较,尽管我将函数'pop'的返回类型设置为int。因此当程序用右括号或大括号处理时它总是打印“未正确嵌套。”我该如何改进?
解决方案
这只是“提及”该功能,而不是调用它。
编译器看到的是函数指针,而不是返回值及其类型。
pop != '{'
采用
pop() != '{'
为了调用函数并比较类型char
和的返回值'{'
。
推荐阅读
- javascript - 无法在 Vue.js 中反应性地删除帖子的评论
- php - 如何在 for 循环中使用 cURL?
- biztalk - BizTalk一一接收定位过程文件?
- elasticsearch - 部署 Elasticsearch 集群的最低资源是哪些?1 个主节点 - 2 个节点
- r - 如何控制逻辑回归中的自变量?
- reactjs - 如何在 React Native 中使用 componentWillUnmount?
- c - 无法理解 Axel Schreiner 的“C 中的 OOP”一书中的上下文
- azure - 重启后Kafka主题被删除
- dart - 飞镖如何获得十位数的时间戳?
- c# - 在一个方法中使用两个 Linq 查询