Reputation: 31
having trouble creating an array of strings of size input by the user. I get the user input for size of the array however I can't pass this value to another function to create an array of strings. Any explanation as to what I am doing wrong here? I am passing by reference the value of the user input to my new function but I get error cannot convert string
to 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];
}
Upvotes: 3
Views: 1753
Reputation: 16
You just need to pass word
by reference, rather than by value, in your getSpace
function. i.e. change *word
to *&word
.
Just remember that if you plan on changing the location a pointer is pointing to, then you need to pass it by reference.
When you say word = new string[arraySize]
in getSpace
, what you are doing is setting word to point at the memory location containing the first element in the new string array.
Upvotes: 0
Reputation: 33931
Ignoring the elephant in the room, std::vector
,
void getSpace(int arraySize, string *word);
specifies a function that takes an int
and a pointer to a string
. Inside the function you assign an array to the pointer of string
s.
A pointer is a variable containing an address, and that address is being passed by value into the function. Inside getSpace
word
is a copy of the address provided by the caller. Both have the same value, point to the same place, but if you change where one is pointing, that change is not reflected in the other. Altering the value of word
does nothing to change the original back in the calling function. You need to pass the pointer by reference to be able to update the pointer back in the caller.
You could define getSpace
as
void getSpace(int arraySize, string * & word);
and call it
getSpace (numStrings, words);
But it would be easier to define it
string * getSpace(int arraySize);
and call it
words = getSpace (numStrings);
Save the hassle. Easier to read, too. By returning the pointer the function clearly gives the caller a pointer to a string. The previous version could be consuming a string, resulting in the uninitialized variable warning Mikhail Genkin mentions in a comment to one of the other answers.
Remember to delete[] words;
when you are done.
Upvotes: 4