PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] How can I pass a class member's fixed size array by reference?

 July 04, 2022     c++, pass-by-reference     No comments   

Issue

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
    }
}

Solution

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();
}


Answered By - Ted Lyngmo
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing