C++ 数组字符串空值

C++ 数组字符串空值,c++,winapi,C++,Winapi,为什么我的IntForItem1超过了阵列字符串的最大长度 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

为什么我的IntForItem1超过了阵列字符串的最大长度

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;
}
inttotalitems=0,IntForItem1=0;
结构项
{
整数指数;
std::string*stringArray=new std::string[555];//随机值,因为它将在GetItems中更改,对吗?
};
项目[120];
int AddNewItem(int i,int Index,std::string stringarray[]))
{
第[i]项。索引=索引;
项[i]。stringArray=stringArray;
返回(i+1);
}
void GetItems()
{
int i=0;
std::string*test=新的std::string[4]{“1”、“2”、“3”、“4”};
i=添加新项目(i,IntForItem1,测试);
总计项目=i;
}
int main()
{
GetItems();
while(true)
{
系统(“CLS”);
对于(int i=0;isizeof(项[0].stringArray)
在您的代码中是
字符串
指针的大小,而不是您设置的空间大小

你可以试试这个


此外,您应该注意数组的大小,否则您总是右键单击数组的大小,可能会导致数组越界,导致程序错误。

如果您从未离开内部while循环,您希望发生什么?为什么使用指向int的指针作为索引?为什么不只是int?如果您想要固定数组,请sider
std::array
此代码泄漏内存您还可以查看
std::vector
类。