我正在尝试刷新我对 C 的记忆。我有一个简单的程序可以检查文本文件中的 HTML 标记,以确保它们都相互匹配。我为此使用了一个堆栈。这是有问题的代码:
char *tag, *endTag;
stackADT stack = newStack();
while (!feof(input))
{
    tag = (char *)malloc(sizeof(char));
    tag = getNextTag(input, &line);
    printf("tag is %s\n", tag);     
    if (*(tag + 1) != '/') //if it is not a closing tag
    {
        push(stack, tag);
        printf("%s was pushed\n", tag);
    }
    else
    {
        endTag = (char *)malloc(sizeof(char));
        endTag = pop(stack);
        printf("%s was popped\n", endTag);
        check = doTagsMatch(endTag, tag);
        if (check == 0)
        {
            printf("Error at line %d: %s and %s do not match.\n", line, endTag, tag);
            exit(1);
        }
    }
    free(tag);
}
从一个带有 html、body 和 p 标签的简单文件,输出如下:
tag is <html>
<html> was pushed
tag is <body>
<body> was pushed
tag is <p>
<p> was pushed
tag is </p>
 was popped
Error at line 1:  and </p> do not match.
我知道堆栈本身可以正常工作,因为我用几个整数做了一个单独的 SSCCE,它工作正常。那是我在程序中唯一使用 endTag 的地方,所以我不明白为什么它没有从 pop 中得到任何东西。我唯一能想到的是它在某种程度上是一个指针问题(如果重要的话,我的堆栈元素是 void*)。