简体   繁体   English

创建一个二维数组,在编译时一维未知

[英]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] ,其中i0..n-1范围内, j0..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.

相关问题 在编译时推导出二维数组的一维 - Deduce one dimension of 2D array at compile time 用静态2d数组定义类的便捷方法是什么(只有在编译时才知道2d数组的大小)? - What is a convenient way to define a class with a static 2d array (and the size of the 2d array is known only during compile time)? 如何正确删除已知第二个维度的二维数组? - How to correctly delete 2d array with known second dimension size? 使用用户定义的尺寸在C ++中创建2D数组(正方形)? - Creating a 2D array (square) in C++ with user defined dimension? 创建整数2d数组(与字符串2d数组相比)而不提及尺寸 - Creating an integer 2d array (as compared to a string 2d array) without mentioning the dimension 最简单的2D数组,使用g ++,具有一个可变维? - Simplest 2D array, using g++, with one variable dimension? 如何返回一维尺寸未知的二维数组? - How to return a 2d array where one dimension is of unknown size? 具有一维常量的二维数组的delete []释放内存 - memory deallocation with delete [] for 2d array with one dimension constant 显示同时具有一个元素的2D数组 - Showing 2D array with one element at the time 在编译时使用给定函数初始化纯2D数组 - Initialize plain 2D array with a given function on compile time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM