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) …
phorce 131 Posting Whiz in Training Featured Poster
karthik_ppts commented: Useful post +6
phorce 131 Posting Whiz in Training Featured Poster