Hello, basically I want to return an array from a function (So I don't output things in the class - just main)
But I seem to get the error: "invalid types 'int[int]' for array subscript"
Here is the code:
#include <iostream>
using namespace std;
int matrix()
{
int matrix[10] =
{
1, 1, 1, 1, 1,
1, 1, 1, 1, 1
};
return *matrix;
}
int main(int argc, char *argv[]) {
int matr = matrix();
for(int i=0; (i < 10); i++)
{
cout << matr[i] << "\t";
}
}
Any help would be great :)
Your code will compile if some changes are made in line 5, 13, 19 as shown below
#include <iostream>
using namespace std;
int* matrix()
{
int matrix[10] =
{
1, 1, 1, 1, 1,
1, 1, 1, 1, 1
};
return matrix;
}
int main(int argc, char *argv[]) {
int* matr = matrix();
for(int i=0; (i < 10); i++)
{
cout << matr[i] << "\t";
}
}
But this is NEVER recommended and there are high chances it might not work. Why? Because the array is defined inside matrix(). So array will reside in the stack area of matrix(). When matrix() goes out of scope (after return to main function) the memory block where the array elements are stored maybe overwritten and hence data loss.
So when you want to return an array from a function either use the static way as suggested by thines01. Or you have to store the array in heap. So even if the function goes out of scope you wont lose your data. It will still be there in heap. But you have to make sure you delete those allocated memory after your use. Here is how you can do it. Note the delete statement at line 22.
#include <iostream>
using namespace std;
int* matrix()
{
int* matrix = new int[10];
for (int i = 0; i < 10; i++) matrix[i] = 1;
return matrix;
}
int main(int argc, char *argv[]) {
int* matr = matrix();
for(int i=0; (i < 10); i++)
{
cout << *(matr+i) << "\t";
}
delete [] matr;
}
Also I have to make clear that the static solution and the heap solution are not same. Both have their own purpose. It's just that in your current case, both will work. Hope you are clear