【发布时间】:2016-08-06 16:27:38
【问题描述】:
在创建用户输入的大小字符串数组时遇到问题。我得到了用户输入的数组大小,但是我不能将此值传递给另一个函数来创建字符串数组。关于我在这里做错了什么的任何解释?我通过引用将用户输入的值传递给我的新函数,但出现错误无法将string 转换为string*
using namespace std;
#include <iostream>
#include <fstream>
#include <string>
//function prototypes
void getSize(int &arraySize);
void getSpace(int arraySize, string *word);
//Calls other functions otherwise does nothing
int main()
{
int numStrings;
string *words;
getSize(numStrings);
getSpace (numStrings, *words);
}//end main
// asks the user how many strings they want
void getSize(int &arraySize){
cout << "How many strings do you want? ";
cin >> arraySize;
}
// gets an array in the heap of the size requested by the user
void getSpace(int arraySize, string *word){
word = new string [arraySize];
}
【问题讨论】:
-
不需要这个指针的东西 --
std::vector<std::string> word(arraySize); -
@PaulMcKenzie 我很感激,但我正在努力学习如何更好地使用指针。不过,感谢您为我提供了一种简单的方法。
-
一般建议:如果不是绝对必要,请不要使用输出参数。 getSize 应该只返回一个 int 并且 - 如果你想坚持使用指针 - getSpace 应该返回一个指向分配数组的指针。
标签: c++ arrays pointers reference pass-by-reference