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

时间:2017-10-18 23:00:47

标签: c++ arrays

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

错误:Error's Image

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)   

以下是代码 CODE的图片。

#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;
}

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

1 个答案:

答案 0 :(得分: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;
}

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

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