C 多维数组中的指针地址 [英] Pointer address in a C multidimensional array

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

问题描述

我正在处理多维数组和指针.我一直在研究一个程序,它打印出一个简单数组的内容和地址.这是我的数组声明:

I'm messing around with multidimensional arrays and pointers. I've been looking at a program that prints out the contents of, and addresses of, a simple array. Here's my array declaration:

int zippo[4][2] = { {2,4},
            {6,8},
            {1,3},
            {5,7}   };

我目前的理解是 zippo 是一个指针,它可以保存其他几个指针的地址.zippo默认保存指针zippo[0]的地址,也可以保存指针zippo[1]的地址,<代码>zippo[2] 和 zippo[3].

My current understanding is that zippo is a pointer, and it can hold the address of a couple of other pointers. By default, zippo holds the address of pointer zippo[0], and it can also hold the addresses of pointers zippo[1], zippo[2], and zippo[3].

现在,请执行以下语句:

Now, take the following statement:

printf("zippo[0] = %p\n", zippo[0]);
printf("  *zippo = %p\n", *zippo);
printf("   zippo = %p\n", zippo);

在我的机器上,输出如下:

On my machine, that gives the following output:

zippo[0] = 0x7fff170e2230
  *zippo = 0x7fff170e2230
   zippo = 0x7fff170e2230

我完全理解为什么 zippo[0]*zippo 具有相同的值.它们都是指针,它们都存储整数 2 的地址(默认情况下),或者 zippo[0][0].但是 zippo 也共享相同的内存地址是怎么回事?zippo 不应该存储指针 zippo[0] 的地址吗?哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇

I perfectly understand why zippo[0] and *zippo have the same value. They're both pointers, and they both store the address (by default) of the integer 2, or zippo[0][0]. But what is up with zippo also sharing the same memory address? Shouldn't zippo be storing the address of the pointer zippo[0]? Whaaaat?

推荐答案

当您声明多维数组时,编译器将其视为一维数组.多维数组只是一种让我们的生活更轻松的抽象.你有一个误解:这不是一个指向 4 个数组的数组,它总是只是一个连续的内存块.

When you declare a multidimensional array, the compiler treats it as a single dimensional array. Multidimensional arrays are just an abstraction to make our life easier. You have a misunderstanding: This isn't one array pointing to 4 arrays, its always just a single contigous block of memory.

在你的情况下,做:

int zippo[4][2]

真的和做的一样

int zippo[8]

使用编译器为您处理的二维寻址所需的数学运算.

With the math required for the 2D addressing handled for you by the compiler.

有关详细信息,请参阅 C++ 中的此数组教程.

For details, see this tutorial on Arrays in C++.

这和做的很不一样:

int** zippo

int* zippo[4]

在本例中,您将创建一个包含四个指针的数组,这些指针可以分配给其他数组.

In this case, you're making an array of four pointers, which could be allocated to other arrays.

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

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