#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars;
return 0;
}
為什么0x7ffffcf9a010當我輸出它時它會回傳?
uj5u.com熱心網友回復:
是的,它會輸出,你看到的奇怪數字是陣列第一個元素的起始地址,cars 被隱式轉換為指標。就其本身而言,它是一個陣列而不是一個指標。
你想這樣做,
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
//cout << cars[0]; // To print the first element
for(int i = 0; i < 4; i )
{
// To print all the elements one by one with a new line in between each element
cout<<cars[i] << '\n';
}
return 0;
}
uj5u.com熱心網友回復:
類似于原始陣列,輸出它的名稱將回傳字串陣列的第一個地址,這里有一個例子。
#include<iostream>
int main() {
std::string str[] = {"This", "is", "a", "string"};
std::cout << str << std::endl; //output 0xc3585ff5b0
int arr[] = {1, 2, 3, 4, 5};
std::cout << arr << std::endl; //output 0xc3585ff590
return 0;
}
uj5u.com熱心網友回復:
它輸出陣列第一個元素(0 索引)的十六進制地址。由于陣列是一種資料結構,這就是它輸出地址的原因。
要更正代碼,您需要執行以下操作:
#include <iostream>
#include <string>
int main() {
std::string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
char string1[100]={"C-style string."};
std::cout << *cars<<"\n";
std::cout<<string1; // does not show hexadecimal address but why?
return 0;
}
現在,此代碼將根據您的需要輸出“Opel”。汽車旁邊的小星號稱為間接運算子。它用于訪問指標指向的值。您的困惑可能來自可以使用 std::cout 一次性輸出的 char 陣列,但 char 陣列是規則的一個例外,字串陣列不一樣。注意(對于現代 C 編程,最好使用 std::array 和 std::vector 而不是老式陣列。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/341807.html
標籤:C
上一篇:C 組合列舉映射
