Structures, Arrays, and 'no match for operator[]'

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:


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
#include <iostream>
using namespace 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.

Also, I'm using DevC++, if that helps.
That's because operator '[]' is not defined for type intArray.
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[]?
Last edited on
I still don't understand
build an array without actually using an array(?)
What does that mean?
Yes, in your 'init' function you will need to do something like:
 
myList.elems = new int[size];


Then,
 
cin >> myList.elems[n];


Since you use a 'new' you will need to remember to clean up after yourself when you are done.

Note: I haven't tried to compile any of this, so it may not work as written.
@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.
Topic archived. No new replies allowed.