D
D
deodox2014-03-12 12:27:04
C++ / C#
deodox, 2014-03-12 12:27:04

How to implement the declaration of a two-dimensional array?

How can you declare a two-dimensional array without knowing its dimensions right away? That is, for example -

int array[][];
int main()
{ array = {{1,2,3,4},{1,2,3,4}}; }

Well, or how to declare a global variable with a two-dimensional array in main?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Morozov, 2014-03-12
@deodox

pointers:

int n, m;
int **a;

//read n
//read m

a = (int **)malloc(sizeof(int *) * n);
for (int i = 0; i < m; i++)
{
  a[i] = (int *)malloc(sizeof(int) * m);
}

for (int i = 0; i < n; i++)
{
  for (int j = 0; j < m; j++)
  {
    a[i][j] = 1;
  }
}

std::vector< std::vector<int> > a;

int n, m;

//read n
//read m

for (int i = 0; i < n; i++)
{
  std::vector<int> v(m);
  for (int j = 0; j < m; j++)
  {
    v[j] = (i + j);
  }
  a.push_back(v);
}

std::cout << a[3][3] << std::endl;

G
GavriKos, 2014-03-12
@GavriKos

Without knowing the size in advance - no way. Use dynamics (pointers), or containers that suit your task.

A
AxisPod, 2014-03-18
@AxisPod

In C++11 std::array, in earlier containers std::list, std::vector, std::deque.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question