c - 指针/函数参数问题?

标签 c pointers c-strings

<分区>

我正在制作一个小程序,它将使用通过动态数组实现的堆栈来检查短语是否具有平衡的圆括号和方括号。到目前为止,我只是尝试将一个短语传递给 isBalanced 函数,然后尝试一个一个地打印出每个字符。当程序到达:

printf("%s\n", nextChar(s));

我收到一个段错误和一条关于传递类型 char 和预期类型 int 的警告。非常感谢任何帮助。

char nextChar(char* s)
 {
        static int i = -1;
        char c;
        ++i;
        c = *(s+i);
        if ( c == '\0' )
            return '\0';
        else
            return c;
}

int isBalanced(char* s)
{
        while(nextChar(s) != 0){
             printf("%s\n", nextChar(s)); 
        }
        return 0;
}

int main(int argc, char* argv[])
{
        char* s=argv[1];
        int res;
        res = isBalanced(s);

        return 0;
}

最佳答案

printf 期望 char *,但是,这段代码

printf("%s", nextChar(s));

给出 char,因为 nextChar(s) 返回 char(如果你使用好的编译器,你必须得到警告)。

所以,把这个改成,

printf("%c\n", nextChar(s)); 

此外,您调用了两次 nextChar(s),丢失了第一次调用的值。
这应该符合您的预期:

int isBalanced(char* s)
{
        char ch;
        while((ch = nextChar(s)) != 0){
             printf("%c\n", ch); 
        }
        return 0;
} 

关于c - 指针/函数参数问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16119331/

相关文章:

c++ - 是否可以将对象转换为不相关的类?

c++ - line.find 不会编译,行未声明

c - 在字符串连接时在我的程序中出现段错误

c 链式困惑

c - 使用带有 while 循环的递归进行十进制到二进制转换

c++ - 这个测试是否证明 malloc、calloc、new 在我的系统上管理它们自己的内存池?

c++ - 用类实例的指针初始化是C++中唯一的吗?

c++ - 指针类型是在声明中调用 "prevent"构造函数的唯一方法吗?

c++ - 返回一个空的 C 字符串

c - 在编译时选择一个函数