I train with pointers and stumbled upon something I don't understand. The program does the following:
- Create vector
- pass the vector address of the function
- This function has for loop
- In this loop, the movie name is requested for the user
- After receiving the name of the movie, a new movie object is created (from the structure)
- A new enhancement stream is created for each film, passing the title created by the user and a pointer for both the new movie object and the vector.
- In the accelerating stream, the variable "title" of the movie object is assigned the title that the user created, and then the movie is added to the vector
- When all threads are executed, the for loop inside the main loop shows all the movie names stored in the vector.
The problem arises when I replace these two
//Get info about new movie from user string movieTitle; int movieYear; //Not used at the moment cout << "Enter title for movie " << (i+1) << endl; getline(cin,movieTitle);
and
//Create new movie movies_t amovie; movies_t * pmovie; pmovie = &amovie;
When I put the "user input part" over the "create a new movie" part, as of now, I get the following:

But when I exchange them:

I do not understand why, because they do not affect each other at all.
Data is displayed as follows:
for(i=0;i<movieVector.size();i++) { cout << movieVector[i].title << endl; }
These are the corresponding functions (main and newThreads)
void newThreads(vector<movies_t> *movieVectorPointer) { boost::thread_group group; //Start thread group int i; for(i=0; i<2; i++) //Make X amount of threads (2 in this case) { //Get info about new movie from user string movieTitle; int movieYear; //Not used at the moment cout << "Enter title for movie " << (i+1) << endl; getline(cin,movieTitle); //Create new movie movies_t amovie; movies_t * pmovie; pmovie = &amovie; //Let user know we are now starting on this thread cout << "Doing thread " << i << endl; //Start new thread newThreadStruct startNewThread(movieTitle,movieYear,pmovie,movieVectorPointer); group.create_thread(startNewThread); } group.join_all(); //Wait for all threads in group to finish } int main() { cout << "Hello world!" << endl; //I am born. vector<movies_t> movieVector; //Create vector to store movies in newThreads(&movieVector); //Start making new threads. Pass movieVector address so it can be used within threads. /* The below code will not be executed until all threads are done */ cout << "Amount of movies " << movieVector.size() << endl; //Let user know how many movies we made //Show all movies we made int i; for(i=0;i<movieVector.size();i++) { cout << movieVector[i].title << endl; } cout << "Bye world!" << endl; //This life has passed. return 0; }
And here is the full code, if that matters:
#include <iostream>
natli source share