C: 格式指定类型 'char *'

标签 c pointers scanf format-specifiers

每当我运行以下代码时,我都会收到错误消息

"format specifies type char * but the argument has type int."

该程序应该打印一个 n x n 正方形或三角形的特定字符。我是 C 的新手,对此进行故障排除我运气不佳。

#include <stdio.h>
#include <ctype.h>

void print_square(int n, char c) {
    for (int i=0; i < n; i++) {
        for (int j; j < n; j++) {
            printf("%c", c);
    }
        printf("\n");
}
}

void print_triangle(int n, char c) {
    int count = 1;
    for (int i=0; i < n; i++) {
        for (int j; j < count; j++) {
            printf("%c", c);
    }
        count = count + 1;
        printf("\n");
    }
}

int main(int argc, const char * argv[]) {

int n;
char cmd;
char * c;

do {

    printf("Enter T for a triangle, S for a square, "
           "Q to quit: ");
    scanf("%c", &cmd);
    cmd = toupper(cmd);

    if (cmd == 'S' || cmd == 'T') {
        printf("Enter the size: ");
        scanf("%d", &n);
        printf("Enter the character: ");
        scanf("%c", *c); // error here

        if (cmd == 'S') {
            print_square(n, *c);
        }

        else {
            print_triangle(n, *c);
        }
    }

} while (cmd != 'T' && cmd != 'S' && cmd != 'Q');

return 0;
}

最佳答案

正如你已经指出的,错误确实在

  scanf("%c", *c);

您需要传递一个指向char 的有效指针,为什么要取消引用?

注意:在您的例子中,您取消引用了一个单元化指针,它调用了 undefined behavior ,无论如何。

要有一个更好的方法(你真的不需要 c 成为那里的指针)做一些像

  char c;
  scanf(" %c", &c);  //the leading space consumes the newline in input bufer

你应该可以开始了。

因此,您需要传递 c 而不是 *c,这是其他函数调用所要求的。

关于C: 格式指定类型 'char *',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35140691/

相关文章:

计算 AES 加密消息的最大长度

c - 内联汇编问题

c++ - 非常量引用的初始值必须是左值

c++ - 指针列表 C++

c - sscanf 1 字节十六进制数据,无溢出

python - 为什么我的 scanf 捕捉到我从 Popen 发出的命令

c - 刷新管道的缓冲区

c - 指向数组的指针和指向指针的指针的内存分配

c - 从文本文件中扫描数据,每个数据项之间没有间距

c - 我程序中的段错误