多维阵列内存存储概述 [英] Multidimensional arrays memory storage overview

查看:85
本文介绍了多维阵列内存存储概述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始学习c ++中的指针和引用(不仅是它们的通常用法,而且还有各种方式,我不想在不久的将来出现问题).

Lately I started learning pointers and references in c++ (not just the usual use of them,but all kinds of ways,I don't want to have problems with them in near future).

在我看来,一维静态分配数组类似于int * const指针.我的问题是,当我使用指针动态分配时,指针本身具有除第一个元素以外的其他内存地址,而在一维数组中则不是这种情况.这是一个例子

From my perspective a 1d static allocated array is similar to a int* const pointer. My problem is that ,when I allocate dynamically with a pointer, the pointer itself has other memory address than the first element,which is not the case in a 1d array. This is an example

int a[5];
cout<<&a<<" "<<&a[0]<<"\n";
int* t=new int[10];
cout<<&t<<" "<<&t[0]<<"\n";

输出为:

0x6afed0 0x6afed0
0x6afecc 0xcb0e40

我不认为1d数组是如何存储的,在1个4字节的块中,您可以存储一个值或一个地址. 我也尝试使用2d数组,并且有更多的交集.

I can't think how the 1d array is stored,at 1 block of 4 bytes you can store either a value or an address. I tried also with 2d arrays,and there are more intersections.

q = new int*[10];
for (i=0;i<10;i++)
    q[i] = new int[i+1];
cout<<&q<<" "<<&q[0]<<" "<<&q[0][0]<<"\n";
int b[10][10];
cout<<&b<<" "<<&b[0]<<" "<<&b[0][0]<<"\n";

输出:

0x6afee4 0xe40e40 0xe41240
0x6afd54 0x6afd54 0x6afd54

如果有人能启发我并解释这些数组的存储方式,我将非常感激.

If someone would enlighten me and explain how these arrays are stored,I would be thankful.

更具体地说,我知道并且逻辑上如何存储由指针使用new关键字动态创建的数组.但是,如果a应该存储a [0]的地址,则& a和& a [0]具有相同的值.那块内存(& a)存储的是a [0]的值,或者a [0]的地址.希望我清楚我的问题所在.

To be more specific, I know and it's logical how the array dynamically created with new keyword by the pointer is stored. But how &a and &a[0] have the same values,if a should store the address of a[0] .That block of memory(&a) stores what then?the value of a[0] or the address of a[0]. Hope I was clear in what my problem is.

推荐答案

t是在堆栈上声明的指针,该指针保存堆上数组的地址. &t获取t的地址,也就是t在堆栈中的位置.如果要访问数组的第一个成员,则可以执行*tt[0].使用括号表示法时,C ++自动根据t的类型取消引用并执行指针运算.

t is a pointer declared on the stack which holds the address of an array on the heap. &t gets the address of t, AKA the location of t on the stack. If you want to access the first member of the array, you can either do *t or t[0]. C++ automatically dereferences and does pointer arithmetic based on the type of t when you use the bracket notation.

但是,&t[0]本质上为您提供了t[0]的地址,这就是为什么它与&t不同的原因,因为&t驻留在堆栈上,而&t[0]驻留在堆上.因此,如果要使用t[0]的地址,则可以使用该表示法,否则,如果只需要这些值,请坚持使用t[0].

However, &t[0] essentially gets you the address of t[0], which is why it is different from &t, as &t lives on the stack while &t[0] lives on the heap. So if you want the address of t[0], you can use that notation, otherwise stick to t[0] if you just want the values.

这篇关于多维阵列内存存储概述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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