C++ Pass a reference to an array to function

前端 未结 3 789
悲&欢浪女
悲&欢浪女 2020-12-17 04:05

Given to functions void main() and void hello(byte* a[4]). Main function has an array of four bytes. The array\'s reference needs to be passed to the function hello for mani

相关标签:
3条回答
  • 2020-12-17 04:50

    Arrays are already passed by pointer.

    So this:

    int a(int array[]) {
    }
    

    Is the same as doing this:

    int a(int * array) {
    }
    

    Doing this:

    void hello(byte (&a)[4])
    

    only allows arrays with a length of 4 to be passed in.

    0 讨论(0)
  • 2020-12-17 04:50

    byte* a[4] is an array of four pointers to byte, except in a parameter list.
    In a parameter list, it is a pointer to a pointer to a byte – i.e. it is equivalent to byte**.

    byte (*a)[4] is a pointer to a four-element array.

    byte (&a)[4] is a reference to a four-element array.

    In your case, &stuff is a pointer to a four-element array, so your parameter should be byte (*a)[4].

    0 讨论(0)
  • 2020-12-17 04:52

    There are many different options here depending on what you want to do here.

    If you have a raw array of byte objects, you can pass it into a function like this:

    void hello(byte arr[]) {
       // Do something with arr
    }
    
    int main() {
       byte arr[4];
       hello(arr);
    }
    

    The mechanism by which the array is passed into the function (a pointer to the first element of the array is passed to the function) functions similarly to pass-by-reference: any changes you make to arr in hello will stick in main even though you didn't explicitly pass in a reference to it. However, the hello function won't check whether the array has size four or not - it'll take in as input an array of any number of bytes.

    You can also write

    void hello(byte (&arr)[4]) {
       // ...
    }
    
    int main() {
        byte arr[4];
        hello(arr);
    }
    

    The syntax byte (&arr)[4] means "a reference to an array of four bytes." This explicitly passes the array by reference into hello, and it will check the size of the array to make sure it's correct. However, this is very unusual syntax and rarely seen in practice.

    But perhaps the best idea is to not use raw arrays and to use std::array instead:

    void hello(std::array<byte, 4>& arr) {
        // Do something with arr
    }
    
    int main() {
        std::array<byte, 4> arr;
        hello(arr);
    }
    

    Now, there's no weirdnesses about strange parentheses in the syntax for arrays of bytes and there's no worries about size checking. Everything is handled properly because std::array is an object type that has all the advantages of regular object types. I'd recommend going with this last approach above all the other ones.

    0 讨论(0)
提交回复
热议问题