I have to initialize an array of string pointers to point to 4 worker names. Then i want to call a function func1() which prints out all the names. And i have to do this using either pass by referebce or values or may be a hybrid of these, anything is fine.
I have already been through following queries of similar type
how to initialize string pointer?
c++ initialization of an array of string pointers
returning array of string from function not working as expected
Also tried to use the Books Deitel and deitel and C++ Primer yet, could not understand or clarify my understanding regarding array of string pointers, to a point that now i am even getting confused with the fundamental basics of this.
Although, having gone through numerous similar questions online i could get only this far, as per the code I have written below.
My Code:-
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void func1(string *str, int *num)
{
for (int i = 0; i <= (*num); i++)
{
cout<<"\n"<<str[i]<<"\n";
}
cout<<"reached to the end of calling function\n\n";
}
int main()
{
int num;
cout<<"\nplease input your prefered size of array\n";
cin >> num; // Number of names elements
cout<<"\nplz enter the desired names\n";
string *str = new string[num];
for (int i=0;i<num;i++)
{
getline(cin, str[i]);
}
cout<<"now printing all the names through a calling function\nusing appropriate parameters\n";
func1(str, &num);
return 0;
}
Present Behaviour:-
Code executes and takes the input from me, but as soon as i give the second-to-the-last value, it gives a prompt error saying "file1.exe has stopped working". However, it does carry on with the remaining task and calls func1() and prints the ending line of the called function.
Output:
please input your prefered size of array
4
plz enter the desired names
Pratik
Pratik Vyas
Pratik Vyas A
now printing all the names through a calling function using appropriate parameters
Pratik
Pratik Vyas
Pratik Vyas A
Process exited after 14.24 seconds with return value 255 Press any key to continue . . .
And i have to close the terminal due to the prompt error that i get as soon as i have entered the third name Pratik Vyas A as described above.
I understand that this may be some really basic level issue, but only if my brain could process other numerous ways given online, that i would have saved this question space for some other worthy important questions. any help appriciated highly.