c - 使用 fprintf 输出 __LINE__ 时出现段错误

标签 c printf

代码如下:

#include <stdio.h>

int main() {

    fprintf(stderr, "%s \n", __LINE__);

    return 0;
}

# gcc b.c
# ./a.out
Segmentation fault (core dumped)

最佳答案

__LINE__ 扩展为整数常量。使用 %d 打印它:

fprintf(stderr, "%d \n", __LINE__);

§6.10.8.1 强制宏(C11 草案)

__LINE__ The presumed line number (within the current source file) of the current source line (an integer constant).


如果 __LINE__ 宏溢出 int 是一个问题,那么您可以将其转换为 uintmax_t 并打印它。这是最安全的方法,因为 uintmax_t 是最大的整数类型。

#include <stdint.h>

fprintf(stderr, "%ju \n", (uintmax_t)__LINE__);

关于c - 使用 fprintf 输出 __LINE__ 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34264316/

相关文章:

c - write vs fprintf - 为什么不同,哪个更好?

c - printf ("%p") 并转换为 (void *)

c - 我不断收到有关传递参数使指针从整数而不进行强制转换的警告

c - 不使用 malloc() 分配 struct dirent

c - make 如何知道要更新哪些文件

C:为什么指针周围有括号?

c - 在 iOS 设备上编写和访问应用程序文件

C Union - 显示一个字节的所有 8 位

c - Printf 数字右对齐

计算数组元素的百分比