Home > Mobile >  How do I access boolean array from another function? c
How do I access boolean array from another function? c

Time:12-15

I have a problem. I need to create a code where I can access bool array information from another function, edit the array and then send it back. I need to use a variable as the size of the array.

Global variable is not an option.

I've tried to pass it by a reference and also using structs.

code for example:

void x(bool (&reserved[sizeOfArray)) {
    if (reserved[1] == true) {
          cout << "it's true";

}    

main() {

int sizeOfArray = 6;
bool reserved[sizeOfArray];

x(reserved[sizeOfArray];

edit: the size of the array is determined when the program is already running

CodePudding user response:

If the size is only determined at runtime, you essentially have two options:

  1. Use a dynamically-sized container, like std::vector

    void x(std::vector<bool>& reserved)

  2. Use the "C method" of passing a pointer to the array's first element along with the array size
    void x(bool reserved[], size_t size)

The possible third option of having a "sentinel" value last in the array (like C-strings) won't work with bool, since you only have two values to choose from.

CodePudding user response:

I think the lightweight method would be to use std::span instead.

#include <iostream>
#include <span>

void x(std::span<bool> reserved) {
    reserved[1] = false;
}    

int main() {

    constexpr size_t sizeOfArray = 6;
    bool reserved[sizeOfArray]{false, true};

    x(reserved);

    if (reserved[1] == false) {
        std::cout << "Hello!" << std::endl;
    }
}

CodePudding user response:

You could make it a function template, with the array size as a template parameter:

#include <iostream>

template<size_t N>
void x(bool (&reserved)[N]) {

    // make sure that the array size is at least 2 to not get out of
    // bounds access in reserved[1]:

    if constexpr (N >= 2) {    
        if (reserved[1] == true) {
            std::cout << "it's true\n";
        }
    }
}    

int main() {
    constexpr size_t sizeOfArray = 6; // must be a constant expression
    
    bool reserved[sizeOfArray]{false,true}; // rest will be false

    x(reserved);
}

Output:

It's true
  • Related