returning two created arrays in c++

arrays, c++, function, pointers

Solution

Whenever you want to group together data items, use a class or a structure. For example, to pass three integers as x, y and z coordinates,:

struct Coord {
   int x, y, z;
};

and then pass the structure to the function:

void f( Coord & c ) {
}

The same goes for arrays, but in your case you would make the structure contain pointers.

Your question actually opens up huge areas of C++ programming that it seems you are not aware of. Some things you should read up on before you go any further:

- the concept of structures, as outlined above

- constructors and destructors for structures

- when and when not to use dynamic memory allocation

- use of C++ standard library containers like std::vector

This may seem a lot, but once you have a clear grip on these, you will find C++ programming much, much easier and safer.

Problem

Hi I have a text file containing two arrays and one value(all integers) like this ``` 3 90 22 5 60 33 24 ``` Where the first number stands for how many integers to read in. I can read in all this in one function. Do I need several functions to be able to use the different matrices and the first variable? ``` ifstream in(SOMEFILE.dat); if (!in) { cerr << "Cannot open file.\n"; return -1;} in >> VAR; A=new int[VAR]; B=new int[VAR]; for(int i=0 ;i<VAR;i++){ in >>A[i]; } for(int i=0 ;i<VAR;i++){ in >>B[i]; } in.close(); ``` Above is the code I have so far and this would work in the main function. Do I have to write three functions to read this info in so I can use it in my program or is there any way I could for example send in three pointers to a function? ``` I would like A to be 90 22 5 B to be 60 33 24 And VAR to be 3 ``` Thanks

Original source