简体   繁体   中英

Creating a 2d array, one dimension not known at compile time

Two things going on I need clarification with: two dimensional array and an array whose length is determined at run time. The first length is unknown, the second is known to be two.

char** mapping = new char*[2];//2d array
mapping[2][0] = 'a';

This program crashes because of memory being written to that is not allocated to the array, how can I fix it? Could you please explain your answer.

If only the first of the array sizes is a run-time value (and the rest are compile-time values), then you can allocate it in one shot. In your case, for run-time size n

char (*mapping)[2] = new char[n][2];

Access this array "as usual", ie as mapping[i][j] , where i is in 0..n-1 range and j is in 0..1 range.

However, unless you have some specific efficiency/layout requirements, it might be better idea to use std::vector .

You need to write:

mapping[1] = new char(1);
mapping[1][0] = 'a';

Every row in the 2D array should be separately initialized and index starts from 0 and maximum available index is 1 but you try to access 3rd 1D array.

Just do it like this and all your problems will be gone:

int size_x = 10, size_y = 20;
char* arr = new char[size_x*size_y];

char get(int x, int y) {
  return arr[x+y*size_x];
}

void set(int x, int y, char val) {
  arr[x+y*size_x]=val;
}

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