c - 无法从 CodeGolf 理解这段代码

标签 c argv puts nul

所以我在 StackOverflow 上失去了我的周末,看到了 this challengeHot Network Questions .

Background

Hello golfers! I would like to learn all the programming languages! But I kinda have a short attention span... and copying all the Hello World examples gets boring... but I like fire! ^w^

Challenge

So here is the plan! I want you all to write the smallest code that will compile, print Goodbye Cruel World!, and then crash. Or, as a bonus twist challenge, print Hello World! and crash with Goodbye Cruel World!

作为一个愿意完全理解C语言的学生,我在偶然发现C answer时感到非常困惑。对这个挑战:

main(){puts(puts("Goodbye Cruel World!"));}

Prints the string and then tries to use the return value as a pointer to another string to be printed, which causes a segmentation fault.

感谢 puts() documentation我发现 puts() 在成功时返回一个非负值。所以如果我理解正确的话,这相当于:

puts(2); 

2 是如何“指向另一个要打印的字符串的指针”??

后来,对这个非常相同的答案进行了改进:

main(i){i=puts("Goodbye Cruel World!")/0;}

这次我完全迷路了。所以i作为main的参数,用来存放puts()的返回值。行。但是 \0 呢?为什么要在那里使用 NUL-TERMINATOR 字符?

如果你能让我轻松一点,理解这一点对我来说会很有趣。另外,我认为如果重新措辞,问题的标题可能会更准确一些,但我无法用语言表达我的误解。

最佳答案

然后回答你的第二个问题:

main(i){i=puts("Goodbye Cruel World!")/0;}

'\0'/0是有区别的 第一个是 NUL 字符,第二个是除以零。所以这段代码试图将 puts 的结果除以零。

关于c - 无法从 CodeGolf 理解这段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484133/

相关文章:

c - 在 C 程序中使用 telnet

c - 为什么使用 argv[] 调用 sscanf() 只能使用一次?

debugging - Tcl 程序,其行为根据 "puts"语句而变化

c++ - Windows 中的 gdb : different behaviour when debugging compiled C and C++ code

c - 如何获取每列中的最小元素并将它们分配到 C 中的新数组中?

c++ - 读取 argv 时 XCode BAD ACCESS

c - 如何打印嵌入空值的字符串,以便用 "(null)"替换 '\0'

ruby - 打印出二维数组

c - 具有 volatile 和非 volatile 成员的 union 的语义是什么?

C: 如何使用 main argv 的参数打开文件?