在单个循环 (C++) 中声明多个变量

Declare many variables in a single loop (C++)

本文关键字:声明 变量 单个 循环 C++      更新时间:2023-10-16

好吧,伙计们,我的问题是,我想声明 24 个变量。我可以使用这一行:

string p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10 ,p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23;

但是,这似乎不是正确的方法,所以我尝试使用循环来为我做这件事。

for (int i = 0;i<=23;++i)
{
    char b = i;
    string p[b];
    p[b] = "-";
    cout << p[b];
}

不要介意关于定义和打印变量的最后一部分,这将改变。然而,问题是这段代码可以工作(编译时没有错误),但立即崩溃(程序.exe停止工作......哪种方法是正确的?

编辑:

很多人似乎不明白:

对不起,我不清楚,p 不是数组。我想在循环中创建变量 p0 然后 p1 等等,但我不知道如何表达这样一个事实,即每个循环的"p"后面的字符都在变化(因此变量)。

您正在尝试为数组中的每个元素"命名"。你根本做不到

只需创建一个大小为 24(从 0 到 23)的数组,不要像现在这样尝试"命名"每个元素,您的元素将被p[0]p[1] .. 直到 p[23]

很难知道你在代码中尝试做什么。这是我最好的猜测:

string p[24];// this allocates your 24-string array
for (int i = 0;i<24;++i)
{
    p[i] = "-";
    cout << p[i];
}

请参阅在开始使用数组之前必须使用固定大小定义数组。您的代码可以编译,但它不会执行您认为的功能。我已经注释了您的原始代码:

for (int i = 0;i<=23;++i)
{
    char b = i;// this seems pointless; basically it does nothing. Keep in mind that a char is just a number. i is already a number.
    string p[b];// allocates an array of strings with b elements. This creates a new, empty, array for *each iteration*. This is definitely not what you want.
    p[b] = "-";// sets the b-th element of the array to "-". This should crash. In a 24-element array, the 24th element is out of bounds. You can only access indices 0-23.
    cout << p[b];
}

第一次在循环中,数组是"size-zero",然后你访问数组末尾的元素。

您正在越界访问数组。

string p[b];
p[b] = "-";

您声明的数组包含b个元素,因此有效索引的范围在 0 到 b -1 之间。但是,您正在尝试在位置b索引。

此外,循环中第一次b为零,不允许大小为 0 的数组。

不清楚你想做什么。您似乎正在尝试使用C++编程打印以下行:

"string p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10 ,p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23;"

而不是实际上在您自己的代码中使用这些变量声明。您是否正在编码以生成另一个代码?

for (int i = 0;i<=23;++i)
{
    char b = i;
    string p[b]; // why do you declare like this? 
    p[b] = "-";
    cout << p[b];
}