Thursday, July 30, 2009

Passing an array of structures in C++?

Basically I have a structure array, TsuPod, looks like this.





struct TsuPod


{


string title;


string artist;


int size;


} songs[NUM_SONGS];





So I use the array of songs[?].title or artist or size in my program. Now I have got everything working in int main so I'm trying to put it all into functions. I have a function in which I set all the values to blank.





In int main I would normally just do this.





for (int q=0; q%26lt;NUM_SONGS; q++)


{


songs[q].title="";


songs[q].artist="";


songs[q].size=0;


}





Now, I am putting this into a function:





void initTsuPod ();


{


for (int q=0; q%26lt;NUM_SONGS; q++)


{


songs[q].title="";


songs[q].artist="";


songs[q].size=0;


}


}





What would I put for the parameters of both the function and the prototype call? Any help in this matter is greatly appreciated.

Passing an array of structures in C++?
Your function prototype is exactly as you have written it; you do not need any parameters:


---------------


void initTsuPod ();


---------------





Put that prototype line in the same header file where you define the struct itself, and you will be fine.





Your function definition has a syntax error though. The semi-colon at the end of the declaration is wrong. It makes the declaration a prototype and the body of the function is incorrectly treated as something different.





It should be like this:


---------------


void initTsuPod () //%26lt;---- notice: no semi-colon here


{


for (int q=0; q%26lt;NUM_SONGS; q++)


{


songs[q].title="";


songs[q].artist="";


songs[q].size=0;


}


}


---------------





You don't need to pass the "songs" array to the the "initTsuPod()" function since the array is defined globally, along with the struct type itself. You did declare the struct globally, right? If you didn't do that then you will have other issues.





But as you have defined it here, anywhere that "TsuPod" struct type is visible, so are the array "songs" and the size "NUM_SONGS" are also visible.





------------


EDIT: I agree with "That Guy". You really should avoid globals whenever you can. but I was just going for the minimum change needed to get the presented code to work.
Reply:I think you are trying to move towards something more like this. Avoid globals when you can.





#include %26lt;iostream%26gt;


#include%26lt;string%26gt;


using namespace std;





struct TsuPod


{


string title;


string artist;


int size;


};








void initTsuPod(TsuPod songs[], int numSongs)


{


for (int q = 0; q %26lt; numSongs; q++)


{


songs[q].title="";


songs[q].artist="";


songs[q].size=0;


}


}








int main()


{


const int NUM_SONGS = 20;





TsuPod songs[NUM_SONGS];





initTsuPod(songs, NUM_SONGS);


}


No comments:

Post a Comment