[英]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.
第一个长度未知,第二个已知为2。
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
就您而言,对于运行时大小
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. “照常”访问此数组,即作为
mapping[i][j]
,其中i
在0..n-1
范围内, j
在0..1
范围内。
However, unless you have some specific efficiency/layout requirements, it might be better idea to use std::vector
. 但是,除非您有一些特定的效率/布局要求,否则最好使用
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. 2D数组中的每一行都应分别初始化,索引从0开始,最大可用索引为1,但是您尝试访问第3个1D数组。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.