首页 > 解决方案 > 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。因此当程序用右括号或大括号处理时它总是打印“未正确嵌套。”我该如何改进?

标签: cpointersstack

解决方案


这只是“提及”该功能,而不是调用它。
编译器看到的是函数指针,而不是返回值及其类型。

pop != '{'

采用

pop() != '{'

为了调用函数并比较类型char和的返回值'{'


推荐阅读