创建2d数组,一个维在编译时不知道 [英] Creating a 2d array, one dimension not known at compile time
问题描述
我需要澄清两件事:二维数组和长度在运行时确定的数组。第一个长度未知,第二个长度为2个。
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.
推荐答案
如果只有第一个数组大小是一个运行时间值是编译时值),那么您可以一次性分配它。在你的情况下,对于运行时大小 n
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];
像往常一样访问此数组,即 mapping [i] j]
,其中 i
位于 0..n-1
范围和 j 在
0..1
范围内。
Access this array "as usual", i.e. as mapping[i][j]
, where i
is in 0..n-1
range and j
is in 0..1
range.
除非你有一些具体的效率/布局要求,最好使用 std :: vector
。
However, unless you have some specific efficiency/layout requirements, it might be better idea to use std::vector
.
这篇关于创建2d数组,一个维在编译时不知道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!