0

For example, I have 2d array of pointers type int. I have two questions. First, how do I declare static 2d array? and how many options I can loop all elements from the 2d array?

  • Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please [edit] your question to include a [mcve] of your own attempt together with a description of the problems you have with it. – Some programmer dude Sep 06 '20 at 17:28
  • 1
    Regarding "2d" arrays, C++ doesn't have multi-dimensional arrays. It can usually be solved by using arrays *of arrays* of some type. – Some programmer dude Sep 06 '20 at 17:29
  • @Someprogrammerdude yes I wonder that too. are not they the same? – laughing Sep 06 '20 at 17:54
  • @laughing the array of arrays is effectively the same untill they are dynamically sized. Then the array of arrays is really an array of pointers to distinct and separate arrays. So, A) the program has "chase" through pointers to find the data arrays and B) the data arrays are not guaranteed to be spatially related. They could be scattered all through memory wherever happened to be found. This damages the CPU's ability take advantage of caching. It can't just Read the entire array all at once. It reads a chunk, finds the next chunk, reads it, etc... The result can be surprisingly slow. – user4581301 Sep 06 '20 at 20:24

1 Answers1

0

You can declare two declare with 2 rows and 5 columns like below:

int** intPtr = new int*[2];
intPtr[0] = new int[5]{ 1,2,3,4,5 };
intPtr[1] = new int[5]{ 6,7,8,9,10 };

You can loop all elements from the 2d array like below:

for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 5; j++)
        cout << *(intPtr[i] + j) << " ";
    cout << "\n";
}

OR

for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 5; j++)
        cout << intPtr[i][j] << " ";
    cout << "\n";
}
laughing
  • 178
  • 1
  • 17
  • 1
    This works, but it is very slow and cumbersome as well as dumping some non-trivial memory management on the programmer's head. [Prefer to use something like this](https://stackoverflow.com/a/2076668/4581301) which stores the whole array in one contiguous block. The `std::vector` handles the memory management for you. – user4581301 Sep 06 '20 at 17:31
  • @user4581301 I know right, everyone said so but I just try to answer what the question is asked. – laughing Sep 06 '20 at 17:49
  • Not dissing the answer. This is what was asked. It's just good to offer up better alternatives when they're available. – user4581301 Sep 06 '20 at 19:32