用C多维数组 [英] Multidimensional arrays in C

查看:137
本文介绍了用C多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据相关人士的意见我对这个问题的回答:的如何把二维数组出来1D之一?

It is related to comments for my answer in this question: How to turn 2d array out of 1d one?

因此​​,考虑这个片断:

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);

我得说,这工作完全正常我的机器上,但我在评论中说,这是纯粹的运气,这是错误的方式申报2维数组,内存应该只有1的malloc分配来获得连续内存。

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.

我真正感到困惑,因为我认为,在C非动态多维数组的工作原理完全一样:他们基本上是一个指针数组,每个值是一个数组

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.

现在的问题是,是不是(便携式,常见的做法等)的方式来做到这一点?我错过关于这一主题的东西吗?我的意思是,我真的看不出有什么问题,这code。

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.

编辑:

我得到了,我终于彻底摆脱了WhozCraig和丹尼尔·菲舍尔评论了解答案。我的主要错误是,我认为数组和指针的相似之处比他们真的是。

I got the answer which I finally understood from comments by WhozCraig and Daniel Fischer. My main mistake was that I assumed that arrays and pointers are more alike than they really are.

主要原因是行优先顺序实际多维数组存储在内存中的线性( HTTP: //en.wikipedia.org/wiki/Row-major_order )。并了解真正的多维数组和我snipppet我建议您阅读这篇文章的实用性差(关于这一主题都作了很好的澄清我和provdes容易理解的例子):

Main reason is row-major order in which actual multidimensional arrays are stored in linear memory (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):

第1部分:的http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c/

2部分: HTTP: //eli.thegreenplace.net/2010/04/06/pointers-vs-arrays-in-c-part-2d/

推荐答案

这个比较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.

这篇关于用C多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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