C#中锯齿状数组的内存分配与C ++中2D数组的内存分配 [英] Memory allocation of Jagged arrays in C# vs 2d arrays memory allocation in C++

查看:77
本文介绍了C#中锯齿状数组的内存分配与C ++中2D数组的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#中的锯齿状数组有一个疑问,因为我在互联网上的某个地方读到有关锯齿状数组的问题,我认为C#中2d锯齿状数组的内存分配与C ++中2d数组的内存分配相同,因为2d锯齿状数组具有一个指针数组,每个指针都指向一个元素数组(例如整数元素),我的意思是在C ++中该数组的内存分配如下:

I have a question about Jagged arrays in C#, as i read about Jagged arrays somewhere on the internet, i think that the memory allocation of 2d Jagged arrays in C# is the same as memory allocation of 2d arrays in C++, because a 2d Jagged array has an array of pointer that each pointer refers to an array of elements (for example integer elements) i mean that memory allocation of the array bellow in C++ :

int** twoDArr {new int* [number1]};
for (int i = 0; i < number1; i++)
{
   twoDArr[i] = new int[number2];
}

与C#中2d锯齿状数组的内存分配相同:

is the same as memory allocation of 2d Jagged arrays in C# :

int[][] 2DJaggedArray = new int[number1][];
for (int i = 0; i < 2DJaggedArray.GetLength(0); i++)
{
    2DJagggedArray[i] = new int[number2];
}

但是我不确定,所以请您告诉我我是否正确,如果可以,请您解释一下C#中2d数组的内存分配如何,例如数组波纹管:

But i am not sure about , So could you please tell me if i am right and if so, could you please explain me how is memory allocation of 2d array in C# for example array bellow:

int[,] 2DArray = new int[number1,number2];

谢谢.

推荐答案

是的,您是对的.C#中的锯齿状数组基本上是内存中的一维数组,其中每个元素只是一个引用.在 for 循环中初始化数组时,它将在内存中的其他位置创建一个新数组,并且引用指向该数组.

Yes you are right. A Jagged array in C# is basically an single dimension array in memory where each element is just an reference. When you initialize the array in the for loop, it creates a new array somewhere else in memory and the reference points to it.

在多维数组( [,] )的情况下,情况大不相同.初始化此类数组时,将创建一个内存块,其大小等于数组所有维度的乘积.从技术上讲,在内存中表示尺寸为 [M,N] 的多维数组的方式与尺寸为 [M * N] 的简单数组的方式相同.多个索引的访问基本上只是语法糖,框架通过维度的乘积来计算元素的实际位置.

In case of multidimensional arrays ([,]), the situation is very different. When you initialize such array, a single block of memory is created and it's size is equal to the product of all dimensions of the array. Technically having a multidimensional array of size [M,N] is represented in memory the same way as a simple array of size [M * N]. The access by multiple indices is basically just a syntactic sugar where the framework calculates the actual position of the element by multiplication of the dimensions.

这篇关于C#中锯齿状数组的内存分配与C ++中2D数组的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆