I'm trying to return an array from boxes function and get it in main function. But I've failed here. The output(from line 4 of boxes.dat) should look like this,
1 2
160 161 162 163
160
But the 2nd line of output is showing 0 instead of 160. If I active or uncomment the 15 and 28 number lines and activate B[] then the it gives correct output with respect to B's values. But I wanted to get data from boxes.dat file.
A is a local variable to the function, so when you return it no longer exists. However, you are returning a pointer to it and trying to access it after that. You're lucky it even works as you have it now.
You can use dynamic allocation to keep it alive after the function terminates, but then the user code needs to know it needs to be deleted at some point. I'd recommend simply having the user pass the array they want to populate with data as a parameter instead of getting it via a return value.
Hi, thanks a lot for reply. I'm trying to solve the problem with both of your suggestions. First I've change the the definition for A. Here is the new code in for loop inside the boxes funciton,
It works fine, but I cannot decide where to put "delete [] A". I put this right before "return boxInARow;" but then it returns incorrect values. If I put it after return boxInRow, it works but would it be valid?
As your second suggestion, my new code is following,
#include <iostream>
#include <fstream>
usingnamespace std;
void boxes(int a, int rows, int* boxInARow) {
ifstream col;
col.open("cols.dat");
ifstream boxData;
boxData.open("boxes.dat");
int i, j;
int NN;
for(i=0; i<rows; i++) {
col>>NN;
int A[NN];
for(j=0;j<NN;j++) {
boxData>>A[j];
}
if(i==a) {
*boxInARow=A;
}
}
boxData.close();
col.close();
}
int main() {
int a=3;
int rows=6;
int boxInARow;
boxes(a,rows, &boxInARow);
cout<<boxInARow[0]<<endl;
}
But it gives me following compilation errors,
test.cpp: In function ‘void boxes(int, int, int*)’:
test.cpp:24:15: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
test.cpp: In function ‘int main()’:
test.cpp:39:19: error: invalid types ‘int[int]’ for array subscript
Please suggest me how to correct them. Thanks again.