Accessing a structure in another function with a pointer

Can I declare an array of structures in a function and access it from other functions without passing it by reference?

ex.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct TsuPod
{
       string title;
       string artist;
       int size;
};

void initTsuPod()
{

   TsuPod songlist[NUM_SONGS];

}


I would then call parts of the array of structures in another function:
1
2
3
4
5
6
7
8
9
void displaySize()
{
     for(int i = 0;i < NUM_SONGS;i++)
     {
         cout << songlist[i].size;

     }

}


I suspect this can be done with pointers but I'm not sure how.

Any advice would be greatly appreciated.

Thanks.
It's not altogether clear what's calling what and in what order.

songlist declared in initTsuPod has the lifetime and scope of that function. When the function returns the variable no longer exists.

If you want a common set of functions have exclusive access to a specific set of variables; well, that's what a class is for.
closed account (D80DSL3A)
If you want variables to be visible within functions without having to pass them then they must be global.
You could use a global array of TsuPods to accomplish this. Many will recommend against this approach though and state that global variables are "evil".

When that global variable is the single thing that the whole program is about though, it makes sense.

Is this the sort of thing you are looking for?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
//#include <iomanip>
#include <string>
//#include<ctime>// for seeding random #'s
using namespace std;

struct TsuPod
{
       string title;
       string artist;
       int size;
	   // a function for convenient initialization of each instance
	   void INIT(const std::string& Title, const std::string& Artist, const int& Size)
	   {
		   title = Title;
		   artist = Artist;
		   size = Size;
	   }
};

const int NUM_SONGS = 3;// # of songs in the list
TsuPod songlist[NUM_SONGS];// global array - no need for initTsuPod() now

void displaySize()
{
     for(int i = 0;i < NUM_SONGS;i++)     
         cout << songlist[i].size << endl;     
}

int main(void)
{
	// initialize each element of array
	songlist[0].INIT("title 1", "artist 1", 3500);
	songlist[1].INIT("title 2", "artist 2", 4000);
	songlist[2].INIT("title 3", "artist 3", 4500);

	// display function
	displaySize();
	
	cout << endl;
	return 0;	
}
Topic archived. No new replies allowed.