如何在 c++ 中定义一个没有大小初始值的数组

How to define an array with no initial value of size in c++

本文关键字:数组 一个 c++ 定义      更新时间:2023-10-16

我正在尝试创建一个程序,该程序获取用户对字符串类型数组的输入,但由于我不知道用户要放入多少项,因此我必须创建空数组,因此当我尝试创建没有初始值的数组时,会出现错误。

错误

:错误的图像

LNK2001 unresolved external symbol "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > * listOfItems" (?listOfItems@@3PAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)   

这是代码代码的图像。

#include "stdafx.h"
#include <iostream>
#include <string>
std::string listOfItems[];
void getInfoToArray()
{
    for (int i = 0;; i++)
    {
        //Get the info of the array.
        std::cin >> listOfItems[i];
        //Check if the user input is -1.
        if (listOfItems[i] == "-1") break;
    }
}
int main()
{
    getInfoToArray();
    return 0;
}

如果有人有比尝试创建一个空数组更好的解决方案,我将不胜感激。

正如注释中所建议的,请尝试使用 std::vector。

但是,如果您确实要使用数组,则必须提前定义数组的大小。

您可以使用 new 命令并在运行时动态设置数组的大小。

   // Example program
#include <iostream>
#include <string>
std::string *listOfItems;
void getInfoToArray(int n)
{
    listOfItems = new std::string[n];
    for (int i = 0;i<n; i++)
    {
        //Get the info of the array.
        std::cin >> listOfItems[i];
        //Check if the user input is -1.
        if (listOfItems[i] == "-1") break;
    }
}
int main()
{
//    getInfoToArray();
    int size;
    std::cout<<"enter size of array"
    std::cin >> size;
        getInfoToArray(size);
    for(int i=0;i<size;i++){
        std::cout<<listOfItems[i]<<"  ";
    }
    return 0;
}

在不从用户那里获得输入的情况下执行此操作的另一种方法是设置预定义的最大大小。这是静态分配,编译时。像这样,

// Example program
#include <iostream>
#include <string>
std::string listOfItems[10];
void getInfoToArray()
{
    for (int i = 0;; i++)
    {
        //Get the info of the array.
        std::cin >> listOfItems[i];
        //Check if the user input is -1.
        if (listOfItems[i] == "-1" && i<9) break;
    }
}
int main()
{
        getInfoToArray();
    return 0;
}

这都是因为内存是在数组的开头分配的,除非您使用指针。

如果您有任何疑问,请随时发表评论

相关文章: