列大小不同的二维数组的动态内存分配
dynamic memory allocation of 2d array in which columns are of different size
我想用c++语言动态创建一个2d数组。但在二维数组中,列的大小应该不同。我的意思是说2d数组不应该在M * n
应该是....
1 2 next line
3 4 5 next line
2 3 4 5 next line
5 next line
4 5 7
我能够以上述方式创建2d数组,但如何显示数组的内容不断为我创建一个问题。谁来给我解释一下这个问题是怎么解决的?
最好的方法是使用向量。它们是可调整大小的数组,可以自动处理所有内存管理。在这种情况下,您可以创建一个二维矢量。
然而,如果出于某种原因你不想使用向量,而想使用c风格的数组,那么你可以通过创建一个指针数组并为每个指针分配不同数量的内存来实现。为了存储它们的大小,我们可以遵循在每个数组中分配一个额外单元格的策略,该单元格将存储该数组的大小。
int main()
{
const int no_of_arrays=10;
int array_size[no_of_arrays]= {1,4,2,4,3,6,8,9,1,3}; // Different size for each array
int *p[no_of_arrays]; // An array of pointers
for(int i=0; i<no_of_arrays; i++)
{
p[i]=new int[array_size[i]+1]; // Allocating
p[i][0]=array_size[i]; // The first cell holds the size of the array
for(int j=1; j<=p[i][0]; j++)
{
p[i][j]=10; // Fill the array with the desired values;
}
}
// Display the arrays
for(int i=0; i<no_of_arrays; i++)
{
for(int j=1; j<=p[i][0]; j++)
{
std::cout<<p[i][j]<<" ";
}
std::cout<<"n";
}
/*
*
* Do your thing with the arrays.
*
*/
// Deallocate the memory allocated to the arrays
for(int i=0; i<no_of_arrays; i++)
{
delete[] p[i];
}
}
但是,不建议使用这样做,因为这会导致很多问题(例如,如果您在new
之后忘记使用delete
,则会导致内存泄漏)。如果事先不知道数组的大小,最好使用vector
相关文章:
- C++ 中动态二维数组的访问冲突
- 在 c++ 中分配布尔值的动态二维数组时超出内存限制
- 尝试从动态分配的二维数组 C++ 中读取值时出现分段错误,并在尝试删除它时给出 munmap_chunk():
- 在 C++ 中交叉动态分配的二维数组时的侵入性值/地址
- 在创建动态二维数组时,在A[i*c+j]中使用c有什么用,即c代表什么
- 如何在C++中将字符串的动态二维数组作为参数传递
- 我需要一个在C 中具有一个动态维度的二维数组
- 如何在C++中动态分配连续的二维数组?
- 动态分配缓冲空间为二维数组 - 为什么失败
- 二维数组中的动态内存分配
- 私有属性C++上的动态二维数组
- 动态创建具有默认值的二维数组C++
- 如何在C++中将动态二维数组传递给函数
- C++ 中动态二维数组中的地址
- 二维数组C++的动态分配
- 如何在C++中动态分配全局二维数组
- 如何在C++中创建动态二维数组
- 为二维数组动态分配内存时出错
- 将动态二维数组的返回指针传递给子函数并对该数组进行寻址
- 需要有关C++中二维数组的动态内存分配的帮助