【发布时间】:2019-09-21 06:40:25
【问题描述】:
为什么我的 IntForItem1 超过了 arrayStrings 的最大长度???
int TotalItems = 0, IntForItem1 = 0;
struct Item
{
int Index;
std::string* stringArray = new std::string[555]; //random value coz it will change in GetItems right?
};
Item item[120];
int AddNewItem(int i, int Index, std::string stringarray[])
{
item[i].Index = Index;
item[i].stringArray = stringarray;
return (i + 1);
}
void GetItems()
{
int i = 0;
std::string * test = new std::string[4]{ "1", "2", "3", "4"};
i = AddNewItem(i, IntForItem1, test);
TotalItems = i;
}
int main()
{
GetItems();
while (true)
{
system("CLS");
for (int i = 0; i < TotalItems; i++)
std::cout << item[i].stringArray[item[i].Index].c_str();
while (true)
{
if (GetAsyncKeyState(VK_LEFT) & 1)
{
if (item[0].Index <= 0)
item[0].Index = 0;
else
item[0].Index -= 1;
break;
}
else if (GetAsyncKeyState(VK_RIGHT) & 1)
{
if (item[0].Index >= sizeof(item[0].stringArray))
item[0].Index = sizeof(item[0].stringArray);
else
item[0].Index += 1;
break;
}
}
}
Sleep(1);
return 0;
}
【问题讨论】:
-
你从未离开过内部的 while 循环,你期望会发生什么?
-
为什么使用指向 int 的指针作为索引?为什么不只是int?另外,如果您想要一个固定数组,请考虑
std::array<std::string, 3> -
此代码泄漏内存
-
您还可以查看
std::vector类。