naveen jayanna
naveen jayanna

Reputation: 119

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

Upvotes: 2

Views: 1207

Answers (5)

Anna
Anna

Reputation: 261

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

Upvotes: 0

Yoav Godelnik
Yoav Godelnik

Reputation: 71

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

Upvotes: 3

jignatius
jignatius

Reputation: 6484

In C++ you can use a std::array of std::arrays 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.

Upvotes: 1

foragerDev
foragerDev

Reputation: 1409

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

Upvotes: 1

Razack
Razack

Reputation: 1896

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

Upvotes: 2

Related Questions