[英]Multidimensional arrays in C
It is related to comments for my answer in this question: How to turn 2d array out of 1d one? 它与这个问题的答案有关: 如何将2d阵列从1d变成1d?
So, consider this snippet: 因此,请考虑以下代码段:
int M = 5;
int N = 5;
int** theArray = (int**) malloc(M*sizeof(int*));
for (int i = 0; i < M; i++)
{
theArray[i] = (int*) malloc(N*sizeof(int));
for(int j = 0 ; j < N; j++)
{
theArray[i][j] = i+j;
printf("%d ", theArray[i][j]);
}
printf("\n");
}
for (int k = 0; k < M; k++)
{
free(theArray[k]);
}
free(theArray);
I gotta say that it works perfectly fine on my machine, but I was told in comments that it is pure luck and it is wrong way to declare 2-dimensional array, that memory should be allocated with only 1 malloc to get contiguous memory. 我必须说它在我的机器上可以很好地工作,但是在评论中告诉我这是纯粹的运气,并且声明二维数组是错误的方法,应该只分配1个malloc内存来获取连续内存。
I'm genuinely perplexed, because I thought that non-dynamic multidimensional arrays in C works exactly the same way: they are basically an array of pointers, where each value is an array. 我真的很困惑,因为我认为C中的非动态多维数组的工作方式完全相同:它们基本上是一个指针数组,其中每个值都是一个数组。
The question is, is it right (portable, common practice etc) way to do this? 问题是,这样做是否正确(便携式,通用做法等)? Did I miss something on this topic?
我有没有想念这个话题? I mean, I really don't see any problem with this code.
我的意思是,我确实没有发现此代码有任何问题。
EDIT: 编辑:
I got the answer which I finally understood from comments by WhozCraig and Daniel Fischer. 从WhozCraig和Daniel Fischer的评论中,我终于得到了答案。 My main mistake was that I assumed that arrays and pointers are more alike than they really are.
我的主要错误是我认为数组和指针比实际更相似。
Main reason is row-major order in which actual multidimensional arrays are stored in linear memory ( http://en.wikipedia.org/wiki/Row-major_order ). 主要原因是实际的多维数组存储在线性内存中的行优先顺序( http://en.wikipedia.org/wiki/Row-major_order )。 And to understand practical difference between real multidimensional arrays and my snipppet I suggest reading this article (it made nice clarification on this topic for me and provdes easy to understand examples):
为了了解实际的多维数组与我的摘录之间的实际区别,我建议阅读这篇文章(它为我很好地阐明了这一主题,并提供了易于理解的示例):
Part 1: http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c/ 第1部分: http : //eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c/
Part 2: http://eli.thegreenplace.net/2010/04/06/pointers-vs-arrays-in-c-part-2d/ 第2部分: http : //eli.thegreenplace.net/2010/04/06/pointers-vs-arrays-in-c-part-2d/
Compare this code: 比较这段代码:
int array[10][10];
for (int i = 0; i < 10 * 10; i++) {
*((int *)array+i) = 0;
}
This is fine for a two dimensional array, as all of the memory is contiguous. 对于所有二维数组,这是很好的,因为所有内存都是连续的。 With your version, you have a contiguous set of pointers, each of which could be pointing anywhere in memory.
在您的版本中,您有一组连续的指针,每个指针都可以指向内存中的任何地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.