The following code works in its parent program. The array only works if it is initialized in main.cpp. While this is not a problem with one, initializing more
in main.cpp can cause a lot of code bloat. Can you please tell me how initiating multiple arrays is done in c++.
1 2 3 4 5 6 7 8 9 10 11 12
main.cpp
..
int number_of_names(0);
cout<<"How many names ?";
cin>>number_of_names;
int array_size = number_of_names;
string * my_array = new string[number_of_names]; //setting up array
//fx calls
input_names(my_array, array_size);
read_back_names(my_array, array_size);
sort_names(my_array, array_size);
string_array is a variable only visible within your initialize_array() function. string_array goes out of scope as soon as your initialize_array() function returns. The memory allocated, though, is still allocated. main() can not access the memory allocated.
#include <iostream>
#include <string>
// A function which allocates an array of size std::strings and returns
// a pointer to the array.
std::string* alloc_array(std::size_t size)
{
returnnew std::string[size];
}
int main()
{
std::size_t capacity = 10;
std::string* strings = alloc_array(capacity);
strings[2] = "Tom";
delete [] strings;
}
#include <iostream>
#include <string>
// A function which allocates an array of size std::strings and returns
// a pointer to the array.
std::string* alloc_array(std::size_t size)
{
returnnew std::string[size];
}
int main()
{
std::size_t capacity = 10;
std::string* strings = alloc_array(capacity);
strings[2] = "Tom";
delete [] strings;
}
why does the array persist after scope terminates in the function?
Because you've dynamically allocated the memory on the heap. That's the whole point (*) of dynamic memory allocation - that you control how long the memory persists for.
The code output was reconstructed with pointers for giggles. The output shows that the init_array fx generates and returns to main the address of the first position of the initilized array, which is supposed to happen. Some people here have posted that you can't see some arrays from main. However in this exercise I can manipulate string_array from main even within other functions. So I am not sure what I am missing there.
I can access the array from anywhere in the program including main. Maybe I don't understand what the author means by "see".
That quote was in response to your second post in this thread. That post contained an earlier version of your code, in which initialize_array was declared as void, so it wasn't returning the pointer. Since the function didn't return the pointer to the dynamically allocated array, there was no way for the calling code to access that memory.
It was in a much later post of yours that you showed us the version of init_array that actually returned the pointer.