在单个循环 (C++) 中声明多个变量
Declare many variables in a single loop (C++)
好吧,伙计们,我的问题是,我想声明 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];
}
相关文章:
- 在疯狂的部分中声明变量
- 如何在C++中为高分辨率时钟声明变量?
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- CUDA 的性能取决于声明变量
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- C++声明变量时自动类型推断而不初始化
- 在不同循环中多次声明变量的优点
- 奇怪的错误 C2131 与 constexpr 声明变量
- 是否可以在 "if" 语句中声明变量?
- 在python-ctypes中声明变量并传递给dll函数
- 在递归函数C++中声明变量
- 只有一个定义/声明时标头声明变量的多堆定义错误
- 奇怪的未声明变量编译器错误
- 我在C++程序中声明变量时遇到问题
- 在命名空间中声明变量
- C++ lambda 按值捕获,而无需更早声明变量
- 声明变量以保存字符串列表时的内存分配
- 如何声明C 变量应突变
- 为什么允许在开关语句中声明变量?但不是声明 初始化
- 在同一命名空间中声明变量和函数是否出错?[C++]