简体   繁体   English

printf %p 返回值

[英]printf %p return value

When I print a memory address with printf %p I get address in hexdecimal - something like 0x7ffee35f5498 .当我用printf %p打印内存地址时,我得到了hexdecimal地址 - 类似于0x7ffee35f5498 I am wondering why the printf return value is 16 and not the actual length of string, in this case 14 ?我想知道为什么printf返回值是16而不是字符串的实际长度,在这种情况下是14

#include <stdio.h>

int     main(void)
{
char    *s = "Hello World!";
int x;

x = printf("%p\n", (void*)&s);
printf("%d\n", x);
return (0);
}

output:输出:

0x7ffeea6a3790 0x7ffeea6a3790

16 16

Address has 14 char but the function returned 16.地址有 14 个字符,但函数返回 16 个字符。

Documentation say's:文档说:

printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error. printf() :它返回打印的字符总数,如果输出错误或编码错误,则返回负值。 ... ...

You're not just printing the address but also a newline after it.您不仅要打印地址,还要在其后打印换行符。 On Linux / MacOS systems a newline is one character (0xA) while on Windows systems it is two characters (0xD 0xA).在 Linux / MacOS 系统上,换行符是一个字符 (0xA),而在 Windows 系统上它是两个字符 (0xD 0xA)。

From your comments, you say you got 15 as your output and that you're on MacOS.根据您的评论,您说您的输出为 15,并且您使用的是 MacOS。 So that's 14 for the printed address plus 1 for the newline which is the expected result.因此,打印地址为 14,换行符为 1,这是预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM