user8195210
user8195210

Reputation:

Passing structure pointer to a function with index vs without

Say I have the prototypes,

void display(const someStruct& ptr);
void display(const someStruct& ptr, int arraySize);

where ptr is of type

simeStruct *ptr = new someStruct[arraySize];

Say that the structure has a variety of members, obviously, and the ptr has already been used to populate. Now, if I want to display the first index, I'd call it as,

someNamespace::display(pKingdom[0]);

implementation being,

void display(const someStruct& ptr) {
    cout << ptr.someMember1 << ", " << ptr.someMember2;
}

Would I be able to call the whole structure here if I used the overloaded function by calling it as,

simeNamespace::display(ptr[arraySize], arraySize);

or is that call invalid? Upon compilation, is it trying to print from the first cell, or is it going to print garbage because the call is incorrect?

Edit: forgot the implementation of overload function

void display(const someStruct& ptr, int arraySize) {
    cout << "SomeOutput is" << endl;
    for (int i = 0; i < arraySize; i++) {
        cout << i + 1 << ". " << ptr.someMember1 << ", " << ptr.someMember2;
    }
}

Upvotes: 0

Views: 346

Answers (1)

Liastre
Liastre

Reputation: 1323

In case void display(const Foo& ref, int arraySize) function awaits object Foo passed, then takes it's reference, that means your method able to change original Foo directly (const gonna prevent this, but as @aschepler mentioned, it's still possible)

To access memory you allocated, you want to pass pointer, it's gonna be like:

void display(const Bar* ptr, int arraySize) {
    for (int i = 0; i < arraySize; i++) {
        std::cout << i + 1 << ") " << ptr[i].a << ", " << ptr[i].b << "\n";
    }
}

Usage display(barPtr, arraySize); where Bar *barPtr = new Bar[arraySize]. Or, if you still wanna pass by reference do like this:

void display(const Bar (&ref)[100], int arraySize) {
    for (int i = 0; i < arraySize; i++) {
        std::cout << i + 1 << ") " << ref[i].a << ", " << ref[i].b << "\n";
    }
}

In this case you need to write size (100 just for example, it can't be variable) in the declaration, and usage display(bar, arraySize);, where Bar bar [arraySize]. Of course you could use template for this:

template <unsigned int N>
void display(const Bar (&ref)[N]) {
    for (int i = 0; i < N; i++) {
        std::cout << i + 1 << ") " << ref[i].a << ", " << ref[i].b << "\n";
    }
}

usage come to display<arraySize>(bar);, where Bar bar [arraySize] your actual object. But, in this case, I would suggest you to use containers, such vector.

Upvotes: 0

Related Questions