/*
Write a program containing the following functions, in this order:
main - calls the other functions; otherwise does almost nothing
getSize - which asks the user how many strings they want
getSpace - which gets an array in the heap of the size requested by the user
inputData - which allows the user to input the strings and stores them
in the array
printData - which prints all the strings, one string per line
destroy - which returns all the space to the heap
All of these functions, except main, shall have a return type of void.
*/
#include <iostream>
#include <string>
usingnamespace std;
void getSize (int *numStrings);
void getSpace (int *numStrings, string newArray[]);
void inputData (int *numStrings, string newArray[]);
/* Calls the other functions; otherwise does almost nothing */
int main ()
{
int numStrings;
string newArray;
getSize (&numStrings);
getSpace (&numStrings, &newArray);
inputData (&numStrings, &newArray);
return 0;
}
/*getSize - which asks the user how many strings they want */
void getSize (int *numStrings)
{
cout << "How many strings would you like? " << endl;
cin >> *numStrings;
}
/*getSpace - which gets an array in the heap of the size requested by the user */
void getSpace (int *numStrings, string newArray[] )
{
newArray = new string [*numStrings];
}
/* inputData - which allows the user to input the strings and stores them */
void inputData (int *numStrings, string newArray[])
{
string data;
for (int i = 0; i < *numStrings; i++)
{
cout << "Please enter string #" << i << endl;
cin >> data;
newArray[i] = data;
cout << newArray[i] << endl;
}
}
string newArray; Lies. newArray is not an array. It is a single variable of type string.
newArray = new string [*numStrings]; You are modifying pointer value. Which is local to function. No changes would be visible outside it. Also there is a memory leak.
inputData (&numStrings, &newArray);
You are passing pointer to single variable. newArray[0] evaluates exactly to that single variable, but newArray[1] (second string entered) is some random memory and behavior is undefined.
How would i fix this??
Sorry im new to pointers and functions in general..
Ive been trying a bunch of other methods but i still cant get it right.
What is the correct way to write functions getSpace? I dont understand how to create an array in a void function and pass it back to main like the assignment asks.. From what I know c++ functions cant return them
string* newArray; //Declares pointer to array
string*getSpace (int numStrings); //Make function return allocated buffer
//Make changes to function yourself
newArray = getSpace(num); //Assign buffer returned from function to your array pointer.