Home > Mobile >  How can I pass a class member's fixed size array by reference?
How can I pass a class member's fixed size array by reference?

Time:06-21

I have a class Node that contains a fixed-size array. I have another class that creates an instance myNode and calls a function to assign 5 values to the fields in the array. I want to pass the array by reference so the function modifies the actual array and not a copy, but I can't figure out how.

Node:

class Node
{
public:
    // Constructor, destructor, other members, etc
    uint8_t mArray[5];
}

Worker:

class worker
{
    void doStuff(uint8_t (&arr)[5])
    {
        arr[0] = 12;
        arr[1] = 34;
        arr[2] = 56;
        arr[3] = 78;
        arr[4] = 90;
    }

    int main()
    {
        Node *myNode = new Node();
        doStuff(myNode->mArray);
        // myNode->mArray is not modified
    }
}

CodePudding user response:

Yes, the array is modified. A minimal reproducible example:

#include <cstdint>
#include <iostream>

class Node {
public:
    uint8_t mArray[5];
};

class worker {
    void doStuff(uint8_t (&arr)[5]) {
        arr[0] = 12;
        arr[1] = 34;
        arr[2] = 56;
        arr[3] = 78;
        arr[4] = 90;
    }

public:
    int main() {
        Node *myNode = new Node();
        doStuff(myNode->mArray);
        for(auto v : myNode->mArray) {
            std::cout << static_cast<unsigned>(v) << ' ';
            std::cout << '\n';
        }
        delete myNode;
        return 0;
    }
};

int main() {
    worker w;
    return w.main();
}

This prints the expected:

12 34 56 78 90 

It'd be easier if you took a Node& in the function though:

#include <cstdint>
#include <iostream>

class Node {
public:
    uint8_t mArray[5];
};

class worker {
    void doStuff(Node& n) {
        n.mArray[0] = 12;
        n.mArray[1] = 34;
        n.mArray[2] = 56;
        n.mArray[3] = 78;
        n.mArray[4] = 90;
        // or just:
        // n = Node{12,34,56,78,90};
    }

public:
    int main() {
        Node *myNode = new Node();
        doStuff(*myNode);
        // ...
        delete myNode;
        return 0;
    }
};

int main() {
    worker w;
    return w.main();
}

CodePudding user response:

A C-style array is never copied when passed by value in a parameter. When passed as an ordinary argument, it decays into a pointer to the first element. So, you don't need to use a reference, just use an ordinary pointer or array parameter.

class worker
{
    void doStuff(uint8_t arr[5]) // same as uint8_t *arr
    {
        arr[0] = 12;
        arr[1] = 34;
        arr[2] = 56;
        arr[3] = 78;
        arr[4] = 90;
    }

    int main()
    {
        Node *myNode = new Node();
        doStuff(myNode->mArray);
    }
}
  • Related