-1

I'm trying to create a pointerlist that points to the previous and next elements. I also want each element to contain an array. How do I define this in the class and/or add the array to the elements of the list

class codes {
    public:
        int code[];
        codes* next;
        codes* previous;
};//codes

void addtolist(codes* & entrance, int k[]) {
    codes* c;
    c = new codes;
    c->code[] = k;
    c->next = entrance;
    if(c->next != NULL){
        c->next->previous=c;
    }//if
    c->previous = NULL;
    entrance = c;
}//addtolist

2 Answers2

2

You create a pointer to some class object like this:

SomeClass *ptr = new SomeClass();

or

 SomeClass a;
 SomeClass *ptr = &a;

To define array inside your structure, just do inside your structure:

int arr[32];

Just note this is array of fized size. If you want array with dynamic size declare:

int * arr;

inside your structure, and then at some point make it point to array objects:

obj.arr = new int[SIZE]; 

You'll have to call delete[] in the above case when done with array. That said it might be tricky (see here) to have class which manages dynamic memory internally, you might prefer array with fixed size.

Do member wise copy of array elements instead of this:

c->code[] = k; // You can't assign like this since code is not a pointer
Community
  • 1
  • 1
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
2

An array is a pointer of sorts already. In C/C++, if I have an array:

int arr[10]

then array access

arr[2];

is just another way of dereferenced pointer access

*(arr + 2);

An array can be passed to a pointer

int getSecond(int* a) {
    return a[2];
}
getSecond(arr);

So, if you class is holding an array whose lifetime is managed somewhere else, all you need is a pointer:

class codes {
    public:
        int* code;
        codes* next;
        codes* previous;
};//codes

Now if you want your codes class to actually manage the lifetime of the array, or copy the values into the class, you will have to do some additional work.

Jay Miller
  • 2,184
  • 12
  • 11