So, I need to write a program that (as far as I can tell) needs me to build an array without actually using an array(?).Based on recent class material, I think I need to use pointers and a created data type. Here's the relevant code:
#include <iostream>
usingnamespace std;
struct intArray {
int size;
int *elems;
};
void initArray(intArray &arr, int size);
int main() {
intArray myList = {0,0};
int numElements = 0;
cout << "How many numbers should be in the list? /n";
cin >> numElements;
initArray(myList, numElements);
return 0;
}
/******************************************************************************/
void initArray(intArray myList, int size) {
for(int n = 0; n < size; n++){
cout << "Please enter a number. /n";
//The problem is here. At 'myList[n]' I get the error
//"no match for 'operator[]' in 'myList[n]'".
cin >> myList[n];
}
}
I know this could be done more easily simply using arrays, but I think the point is to learn how to do this with pointers and structures instead. Otherwise, I'd have no problem getting it to build an array.
To elaborate, you'd either need to overload the [] operator for your intArray struct, or you'd need to do myList.elems[n]
EDIT:
Also, even if this code compiles it would likely crash as soon as you try to run it. myList.elems is a null pointer, so you can't dereference it. You need to make it actually point to something. I assume you meant to allocate space for an array with new[]?
@histrungalot Yeah, I didn't really understand what I was trying to say either. But hey, I got the program to work (basically did the same thing as sadavied said), and the rest of it all fell into place, so I think I'm good now! And thanks everyone for the help.