多维数组和指针数组之间的区别 [英] Difference between multi dimensional arrays and array of pointers

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

问题描述

我一直相信在C中:

int a[5][3]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

是指数组的数组,在内存中存储了15个连续的块,但是a[0]是指向a[0][0]的指针,而a[1]是指向a[1][0]的指针,依此类推.因此,我认为它类似于指针数组.它们之间有什么区别?

refers to an array of arrays and in memory fifteen contiguous blocks are stored but a[0] is the pointer to a[0][0] and a[1] is the pointer to a[1][0] and so on. So I thought it to be similar to be an array of pointers. What is the difference between them?

推荐答案

在C(和C ++)中,数组和指针有着非常奇妙而亲密的关系.在大多数情况下,如果您拥有的是"X数组",则它将被无提示转换为指向该数组第一个元素的"X指针".

Arrays and pointers have a very curious and intimate relationship in C (and C++). In most contexts, if you have something that is an 'array of X', then it will be silently converted to a 'pointer to X' that points at the first element of the array.

您的信念

int a[5][3];

创建一个数组数组是完全正确的.根据声明,它是一个array of 5 arrays of 3 ints,它在内存中占据15个连续的整数.

creates an array of arrays is entirely correct. According to the declaration, it is an array of 5 arrays of 3 ints and it occupies 15 contiguous integers in memory.

您出错的地方是相信a[0]是一个指针.实际上,a[0]a的第一个子数组,并且本身是array of 3 ints.但是,由于指针和数组之间存在奇怪的关系,因此表达式a[0]几乎总是转换为指针.

Where you go wrong is in believing a[0] to be a pointer. In fact, a[0] is the first sub-array of a and is itself an array of 3 ints. However, due to the curious relationship between pointers and arrays, the expression a[0] is almost always converted to a pointer.

数组数组和指针数组之间的主要区别之一是数组元素所在的位置.数组数组将始终占据一个连续的内存块,但是指针数组中的指针将各自引用它们自己的(通常是不相交的)内存块.

One of the major differences between an array of arrays and an array of pointers is in where the array elements reside. An array of arrays will always occupy a contiguous block of memory, but the pointers in an array of pointers will each refer to their own (often disjoint) blocks of memory.

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

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