c - C中函数的返回值

标签 c stack return return-value return-type

我尝试编写一些代码来使用以下函数检查表达式中的括号是否为余额。有人可以帮助我理解为什么在平衡表达式的情况下没有在任何地方指定返回 1 时下面的函数返回 1。

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

struct Stack
{
    int top;
    unsigned capacity;
    char* array;
};

struct Stack* createStack (unsigned capacity)
{
    struct Stack* stack = (struct Stack*) malloc (sizeof(struct Stack));
    if(!stack)
        return NULL;

stack->top = -1;
stack->capacity = capacity;
stack->array = (char*) malloc(stack->capacity * sizeof(int));

if (!stack->array)
    return NULL;
return stack;
}

int isEmpty(struct Stack* stack)
{
    return (stack->top == -1);
}
void push(struct Stack* stack, char op)
{
    stack->top++;
    stack->array[stack->top] = op;

}

int pop(struct Stack* stack)
{

    if (!isEmpty(stack))
        return (stack->array[stack->top--]);
    return '$';
}

int isMatchingPair(char char1 , char char2)
{
    if (char1 == '(' && char2 == ')')
        return 1;
    else if (char1 == '[' && char2 == ']')
        return 1;
    else if (char1 == '{' && char2 == '}')
        return 1;
    else
        return 0;
}

int paranthesesMatch(char* exp)
{
    int i;
    struct Stack* stack = createStack(strlen(exp));
    for(i = 0; exp[i]; i++)
    {
        if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
        push(stack , exp[i]);
       if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}')
       {
        if (stack == NULL)
            return 0;
        else if ( !isMatchingPair(pop(stack), exp[i]) )
           return 0;

       }
    }
}

int main()
{
  char exp[100] = "{()}[)";
  printf(" %d\n", paranthesesMatch(exp));
  if (paranthesesMatch(exp) == 1)
    printf("Balanced \n");
  else
    printf("Not Balanced \n");  
   return 0;
}  

编辑:添加了完整代码。

最佳答案

您的函数返回 1 是未定义行为的结果。编译器可以自由地做任何它想做的事,因为并非函数中的所有执行路径都会产生返回语句。

可能似乎起作用的原因是调用者(不知道函数在没有返回语句的情况下完成)试图访问返回值(可能在指定的寄存器中) .并且您的函数在返回给调用者之前修改了所述寄存器。

在构建时提高你的警告级别,将产生一个关于它的诊断(like so)。您应该考虑将该特定警告升级为错误,因为省略 return 语句会导致难以发现的错误。

关于c - C中函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207006/

相关文章:

java - 尽管满足条件,但方法从未到达 if 语句

c - 如何在C中正确返回字符串

c - 程序C 简单的小程序错误

java - 将 jchararray 分配给 const unsigned char

C——修改栈基指针地址

c++ - 在恒定时间内找到堆栈中的最大元素

C 中包含 ljpeg 库时出现编译错误

c - 尝试根据用户输入制作马里奥金字塔。但是,如果遇到 get int 问题,我可以获得帮助吗?

c++ - 为什么这不会在 WSL 中的 Ubuntu 上触发堆栈溢出?

python - 深度递归(Python)