简体   繁体   中英

Struct's pointer and how to access elements

i wanted to create a little example for struct's witch constructor and destructor, but my problem is that i can't "print" Zahlen[0] and i don't know why?

Thank for any kind of help.

Maybe i have to print it with pointer argument?

#include <iostream>
using namespace std;

struct IntList{
    int *memory;
    int size;

    // Konstruktur
    IntList(unsigned initialSize = 0) {
        memory = new int[initialSize];// Speicher reservieren (0 erlaubt)
        size = initialSize;
    }

    //Destruktor
    ~IntList() {
        delete []memory; // Speicher freigeben
    }

    // Access Elemnts
    int &operator[](unsigned index) {
        if (index>=size) {throw std::out_of_range("out of bounds");}
        return memory[index];
    }
};



int main()
{
    IntList *Numbers = new IntList(10);
    Numbers[0] = 1;
    cout << Numbers[0] << endl;
    delete Numbers;

    return 0;
}
IntList *Numbers = new IntList(10);
Numbers[0] = 1;
cout << Numbers[0] << endl;

Numbers are of type pointer-to-IntList. Pointers have had array-like semantics in C family since time immemorial, so Numbers[0] is not a call to IntList::operator[] but rather merely a pointer's first element, that IntList you've allocated on heap.

Either create it on stack:

IntList Numbers(10);
Numbers[0] = 1;
cout << Numbers[0] << endl;
// automatically destroyed on exiting scope

Or at least address it correctly:

IntList *Numbers = new IntList(10);
(*Numbers)[0] = 1;
cout << (*Numbers)[0] << endl;
delete Numbers;

The problem here is you made Numbers a pointer to a IntList . IntList *Numbers = new IntList(10); needs to be IntList Numbers = IntList(10); so that you have a IntList object and not a pointer to one. This will allow you to call IntList::operator[] instead of the operator[] of the pointer which just gives you an Intlist

Then you need to get rid of delete Numbers; as well since Numbers is no longer a pointer.

You want to write

IntList Numbers(10);
Numbers[0] = 1;
cout << Numbers[0] << endl;

The issue with your snippet

IntList *Numbers;
auto thisIsNotWhatYouThinkItIs = Numbers[0];

is that the second statement returns IntList because Numbers is a pointer to the IntList instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM