【问题标题】:What does 0 in printf( 0, "%d", num) do?printf(0, "%d", num) 中的 0 有什么作用?
【发布时间】:2023-03-28 10:32:01
【问题描述】:

我通常使用 C++ 编写代码,但我正在使用 C 编写一个项目,我遇到了一个具有以下语法的 printf:

printf( 0, "%d\n", num);

我环顾四周,找不到关于 printf 中第一个 0 的作用的解释。有人可以向我解释一下吗?谢谢。

【问题讨论】:

  • 因为你应该得到警告! [Warning] null argument where non-null required (argument 1) [-Wnonnull][Warning] too many arguments for format [-Wformat-extra-args]
  • 你确定不是fprintf
  • @PaulR 即使它是 fprintf() 也只是 (FILE *)0... 除非它是打印到文件描述符并在 POSIX.1-2008 中指定的 dprintf() .

标签: c arguments printf


【解决方案1】:

因为xv6 没有使用标准库中的printf

void
printf(int fd, char *fmt, ...)
{
    char *s;
    int c, i, state;
    uint *ap;
    state = 0;
    ap = (uint*)(void*)&fmt + 1;
    for(i = 0; fmt[i]; i++){
        c = fmt[i] & 0xff;
        if(state == 0){
            if(c == '%'){
                state = '%';
            } else {
                putc(fd, c);
            }
        } else if(state == '%'){
            if(c == 'd'){
                printint(fd, *ap, 10, 1);
                ap++;
            } else if(c == 'x' || c == 'p'){
                printint(fd, *ap, 16, 0);
                ap++;
            } else if(c == 's'){
                s = (char*)*ap;
                ap++;
                if(s == 0)
                    s = "(null)";
                while(*s != 0){
                    putc(fd, *s);
                    s++;
                }
            } else if(c == 'c'){
                putc(fd, *ap);
                ap++;
            } else if(c == '%'){
                putc(fd, c);
            } else {
            // Unknown % sequence. Print it to draw attention.
                putc(fd, '%');
                putc(fd, c);
            }
            state = 0;
        }
    }
}

【讨论】:

  • 他们真的用这个名字来表示这样的功能,即使在 POSIX.1-2008 中指定了dprintf()?跨度>
【解决方案2】:

undefined behavior;我猜你可能有分段违规。

【讨论】:

  • 这会编译、运行和打印语句。我在 xv6 的代码中看到了它。
  • @Caulibrot 取消引用 NULL 指针是未定义的行为,因此任何行为都是可能的,因为它是 未定义,它可能是 分段错误 或它可以工作,或者任何其他行为,它是 undefined...
  • @kamituel 我不这么认为,如果它是 write(0 ... 好的,但在这种情况下,OP 通过 0 获取格式字符串,该格式字符串将被取消引用而不检查 NULL 中的 @ 987654326@.
  • 我在 xv6 的程序集 (ls.asm) 文件中找到了以下函数: void printf( int fd, char * fmt, ... ) 我猜这会以某种方式使用 0 ,但我不确定具体是怎样的。
【解决方案3】:
printf( 0, "%d\n", num);

调用未定义的行为,因为printf 的第一个参数必须是指向字符串的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多