简体   繁体   中英

How to declare a static 2D array within a function in C++?

I need to declare a 2D array within a function and call the function repeatedly but the array should be declared only once at the beginning. How can I do this? I'm new to this. thanks in advance

Static Variables inside Functions

Static variables when used inside function are initialized only once, and then they hold there value even through function calls.

These static variables are stored on static storage area, not in stack.

consider the following code:

#include <iostream>
#include <string>

void counter()
{
    static int count[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    static int index = 0;

    std::cout << count[index / 3][index % 3];
    index++;
}

int main()
{
    for(int i=0; i < 9; i++)
    {
        counter();
    }
}

Output:

123456789
void func1()
{
    static int myArra[10][20];
}

As Razack mentioned. That is the first way. and the second way is using std::array so you can accomplish like this.

#include <array>
void fun(){
    static std::array<std::array<int, 5>,5> matrix;
}

In C++ you can use a std::array of std::array s to create a 2D array:

#include <array>

std::array<std::array<int, 3>, 3> arr = { {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}} };

This is a 3 x 3 2D array with each element initialised to 0. The syntax for accessing an element is the same as a C-style 2D array: arr[row][col] .

It could be declared static within your function, but it could also be declared within an anonymous namespace at the top of your.cpp file like this:

namespace
{
   std::array<std::array<int, 3>, 3> arr = { {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}} };
}

This is generally better practice than static variables. The array is initialised only once before the main thread starts and only functions within your translation unit (your.cpp file) have access to it.

void process(int ele, int index) {
    static std::vector<std::vector<int>> xx_vec = {{1,2,3}, {11,12}, {}};
    // example:
    for (int i = 0; i < xx_vec.size(); i++) {
        // add
        if (index == i) {
            xx_vec[i].push_back(ele);
        }
        // read
        for (int j = 0; j < xx_vec[i].size(); j++) {
            std::cout << "xx_vec" << "place:" << i << "," << j << ":" << xx_vec[i][j] << std::endl;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM