HebrewHammer wrote: |
---|
My thought process was that I could have an array of pointers (of type 'record') that pointed to arrays (of type 'record'). [...] But out of curiosity, why doesn't my code work? |
Your logic is correct, you just had some trouble implementing it. If you want to use arrays, the solution should look like this:
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <iostream>
using namespace std;
struct Record
{
int a;
int b;
};
const int NUM=3;
const int SIZE=5;
Record * concatenate();
Record * import_data(int n);
int main()
{
Record * big_array=concatenate();
for (int i=0; i<NUM*SIZE; i++)
{
cout << '(' << big_array[i].a << ',';
cout << big_array[i].b << ')' << endl;
}
//cleanup
delete[] big_array;
cout << "\nhit enter to quit...";
cin.get();
return 0;
}
Record * concatenate()
{
//that's what you want here
Record * array_of_pointers[NUM];
int i,j;
for (i=0; i<NUM; i++)
array_of_pointers[i]=import_data(i);
Record * result=new Record[NUM*SIZE];
for (i=0; i<NUM; i++)
{
for (j=0; j<SIZE; j++)
{
result[j+i*SIZE]=
array_of_pointers[i][j];
}
}
//cleanup
for (i=0; i<NUM; i++)
delete[] array_of_pointers[i];
return result;
}
Record * import_data(int n)
{
Record * data=new Record[SIZE];
for (int i=0; i<SIZE; i++)
{
data[i].a=n;
data[i].b=i;
}
return data;
}
|
The good things with vectors are that you don't have to do the cleanup manually, your 'small' containers may vary in size independently, and the number and size of your 'small' containers may be determined in run-time
(you could still pull the last two off using arrays, but it would be trickier and more verbose).
PS: Just in case you didn't notice yet, there's a very good tutorial in this site that could help a lot:
http://cplusplus.com/doc/tutorial/
http://cplusplus.com/doc/tutorial/pointers/
fun2code wrote: |
---|
Wow, I did not know that an array can have only 1 or even 0 elements! |
Mmmm... After reading your post in the lounge, I thought that your first post here was a bluff to test the OP.
I guess it wasn't... Or maybe it was, and this here is a second bluff to support the first one xD
I guess you're the only one who knows for real :P