在字符串中[0]和[0]有什么區別

[英]what is the difference between a[0] and &a[0] in string


string a = "asdf";
cout<<&a[0];
cout<<a[0];

Why are these two outputs different? Why is &a[0] not the address but the whole string?

為什么這兩個輸出不同?為什么&a[0]不是地址而是整個字符串?

3 个解决方案

#1


13  

&a[0] has type char *. Stream operator << is deliberately overloaded for const char * arguments to output zero-terminated string (C-style string) that begins at that address. E.g. if you do

bb&a b0有char類型*。流操作符< <被故意重載,以便const char *參數輸出從該地址開始的零終止字符串(c風格的字符串)。例如,如果你< p>

const char *p = "Hello World!";
cout << p;

it is that overloaded version of << that makes sure the "Hello World!" string itself is sent to output, not the pointer value.

是重載的<< < <確保“hello world!”字符串本身被發送到輸出,而不是指針值。< p>

And this is exactly what makes your code to output the entire string as well. Since C++11 std::string objects are required to store their data as zero-terminated strings and &a[0] is nothing else than a pointer to the beginning of the string stored inside your a object.

這就是代碼輸出整個字符串的原因。由於C+ 11 std::string對象被要求將其數據存儲為零終止字符串,而[0]只不過是存儲在&a對象中的字符串開頭的指針。

#2


1  

&a[0] yields type char*. This is a type for which operator<<() is overloaded. This particular overload prints the characters starting at the address until it finds a null-character, '\0'. It won't print the address like you'd expect.

和[0]收益率char *類型。這是一個操作符<<()被重載的類型。這個特殊的重載打印從地址開始的字符,直到找到一個空字符'\0'。它不會像你預期的那樣打印地址。

Since you need the address, there's std::addressof() in the standard library:

由於需要地址,標准庫中有std::addressof():

std::cout << std::addressof(a[0]);

you can also cast to void* which is almost like the above variant:

你也可以施放到void*,這幾乎和上面的變體一樣:

std::cout << static_cast<void*>(&a[0]);

#3


1  

When printing a pointer to a standard library output stream, if it's char* or const char*, the null-terminated string pointed to will be printed, rather than the address itself. If you want to have the address printed:

當打印指向標准庫輸出流的指針時,如果是char*或const char*,則將打印指向的以null結尾的字符串,而不是地址本身。如要印上地址:

cout << static_cast<const void*>(&a[0]);

(Trivia: if the pointer type isn't convertible to const void* either---because it is a function pointer or a pointer to member or it is volatile---then it is converted to bool.)

(瑣事:如果指針類型也不能轉換為const void*——因為它是一個函數指針或成員指針,或者它是易變的——那么它就被轉換為bool。)


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/01/26/2c52c64c888fbbccd36cffb963dbfc94.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com