简体   繁体   English

printf() 和 std::cout 在指针方面的区别

[英]difference between printf() and std::cout with respect to pointers

I am new to pointers and i cant figure out one simple thing.我是指针的新手,我无法弄清楚一件简单的事情。

   int main ()
{
    char *str1="pointer";
    printf("%p \n", str1);
    cout << str1<<endl;
    return 0;
}

The output is as follows :输出如下:

0000000000409001
pointer

Could someone please explain me the difference here.有人可以解释一下这里的区别吗。 why isnt cout printing the memory address ?为什么不打印内存地址? how can i make cout print the address of str1?如何让 cout 打印 str1 的地址?

The format specifier %p prints a void * , (untrue: so the char * is implicitly converted to void * ) the char * is converted to void * before printing.格式说明符%p打印一个void * ,(不真实:所以char *隐式转换为void *char * void *在打印之前转换为void * (But this is actually undefined behavior, see comments. The correct way to do that would be printf("%p", (void *) str1); ) The corresponding C++ code would be std::cout << (void *) str1 << '\\n'; (但这实际上是未定义的行为,请参阅注释。正确的方法是printf("%p", (void *) str1); )相应的 C++ 代码将是std::cout << (void *) str1 << '\\n'; . .

The code std::cout << str1;代码std::cout << str1; prints str1 as null terminated string.str1打印为空终止字符串。 The corresponding C-code would be printf('%s', str1);相应的 C 代码将是printf('%s', str1);

A pointer is an address to a location in memory.指针是指向内存中某个位置的地址。

"pointer" is a C-string in memory, 8 bytes for the letters and a terminating NULL byte. "pointer"是内存中的一个 C 字符串,8 个字节的字母和一个终止的 NULL 字节。 str1 is a pointer to the byte of the first letter 'p' . str1是指向第一个字母'p'的字节的指针。


printf("%p", str1) prints the value of the pointer itself, that is the memory address (in this case 0000000000409001 ). printf("%p", str1)打印指针本身的值,即内存地址(在本例中为0000000000409001 )。

printf("%s", str1) would print pointer , the content of the C-string at location str1 . printf("%s", str1)将打印pointer ,即位置str1处的 C 字符串的内容。


cout << str1 << endl also prints the content of the C-string. cout << str1 << endl还会打印 C 字符串的内容。 This is the default behavior for pointer of type char* because they are usually strings.这是char*类型指针的默认行为,因为它们通常是字符串。

cout << static_cast<void*>(str1) << endl would print the address of the pointer again. cout << static_cast<void*>(str1) << endl将再次打印指针的地址。

a char* is a pointer to the beginning of an array of characters. char* 是指向字符数组开头的指针。

cout "recognizes" a char* and treats it like a string. cout “识别”一个 char* 并将其视为字符串。

You are explicitly telling printf() to print out the decimal representation of a pointer address with the %p formatter. 您明确告诉 printf() 使用 %p 格式化程序打印出指针地址的十进制表示。

You are explicitly telling printf() to print out a representation of the pointer address with the %p formatter.您明确告诉 printf() 使用 %p 格式化程序打印出指针地址的表示

EDIT: edited for accuracy based on comment编辑:根据评论为准确性进行编辑

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

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