为什么打印字符串阵列输出十六进制



为什么以下程序打印" 0x2ffee4"?

#include <string>
#include <iostream>
using namespace std;
int main() {
    string city1[] = "toronto";
    cout << city1;
    return 0;
}

第一行不应该编译,但是有一个GCC错误使其编译并表现为

之类的东西
std::string city1[] = {"toronto", "toronto", "toronto", "toronto",
                       "toronto", "toronto", "toronto", "toronto"};

(8,因为 "toronto"是8个字符,包括终端null。是的,这意味着,如果您使用"Chargoggagoggmanchauggagoggchaubunagungamaugg",它将创建一个46个字符串的数组,每个字符串,每个存储"Chargoggagoggmanchauggagoggchaubunagungamaugg"。)

不必说,您不应该依靠编译器错误。

在GCC的错误行为下,city1将是std::string s的数组;没有操作员<<超载支持打印此类内容。相反,在std::cout << city1中,数组腐烂到指向其第一个元素的指针,而存储在指针中的地址则是打印的。

您可能打算写std::string city1 = "toronto";。一个字符串,不是它的数组。

T.C.给出的答案是正确的,我还想提到,如果您期望使用COUT将"多伦多"打印到控制台,那么您将要执行此操作:

include <string>
include <iostream>
int main() {
    using namespace std;
    // string city1[] = "toronto"; // Compiler Error - Do Next Line Instead
    string city1[] = { "toronto" };
    cout << city1[0];
    return 0;
}

任何时候要在声明期间初始化任何类型的数组,您需要使用= {};要设置每个数组的元素,以逗号分隔。查看此代码示例:

#include <string>
#include <iostream>
int main() {
    using namespace std;
    string cities[] = { "New York", "Philadelphia", "Chicago", "Boston" };
    // Same As Above Except Size Of Array Is Defined First Then The Elements
    string cities[4];
    cities[0] = "New York";
    cities[1] = "Philadelphia";
    cities[2] = "Chicago";
    cities[3] = "Boston";
    unsigned index = 0;
    for ( ; index < 4; index++ ) {
        cout << cities[index] << endl;
    }
    return 0;
}

如果您在声明数组时不初始化数组,则必须指定数组的大小。

int main() {
    int iArray[]; // Compiler Error
    int iArray[] = { 4, 3, 2, 1, 6 }; // Okay and is the same as
    int iArray[5];  // Okay
    iArray[0] = 4;
    iArray[1] = 3;
    iArray[2] = 2;
    iArray[3] = 1;
    iArray[4] = 6;
    return 0;

}

如果您不使用带有索引值的支架运算符发送到控制台输出流std :: cout,则您获得的十六进制值是正确的T.C已经说过;它正在返回第一个索引的地址。这就是为什么在C/C 阵列和指针中相似的原因(它们不一样,但几乎彼此相似)。与数组的主要区别在于它们的尺寸是恒定的,大小必须在编译时知道,并且在创建具有较大尺寸的新数组的同时,不必将内容存储到温度变量中,而无需将内容存储到温度变量中,而无需将内容存储到temp变量中,则不能动态更改大小。然后将所有数据复制到新数组中,然后清理旧数组。使用指针,它们不会以这种方式行为,可以使用新的新指针在堆上动态分配,但如果该变量不再使用以防止内存泄漏,则必须删除指针,如果指针在手动之前已删除并且有东西试图访问它,则必须删除该内存地址不再有效,也不属于呼叫者,通常被视为未经手的异常,堆损坏等,并且会使您的程序崩溃。当您尝试将它们索引到它们的边界时,数组也是如此。

#include <iostream>
int main() {
    // Arrays Are 0 Indexed
    int iArray[3] = { 1, 2, 3 };
    // If you try to do this to access the last element
    std::cout << iArray[3] << std::endl; // Program Will Crash
    // Since Arrays Are 0 Indexed And The Size Of The Array Is 3
    // The 3rd Value Is Indexed At 2, And By Trying To Index Location Of Array
    // At 3, This Memory Doesn't Belong To You, And It Is Undefined Behavior.
    // This Memory Could Contain Nothing, Random Data, Or Even Data That Belongs To 
    // Something Else Which If Changed Can Even Cause System Failure          
    return 0;
} 

最新更新