【问题标题】:Array String null数组字符串空
【发布时间】: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&lt;std::string, 3&gt;
  • 此代码泄漏内存
  • 您还可以查看std::vector 类。

标签: c++ winapi


【解决方案1】:

您代码中的sizeof(item[0].stringArray)string 指针的大小,而不是您设置的空间大小。

你可以试试这个。

另外,你要注意你的数组的大小,否则你会一直右键单击数组的大小,会导致数组越界,导致程序错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2013-11-29
    • 2016-05-30
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多