是什么INT之间的差* X [n]的[米]和INT(* X)[n]的[米] [英] What is the difference between int* x[n][m] and int (*x) [n][m]?

查看:149
本文介绍了是什么INT之间的差* X [n]的[米]和INT(* X)[n]的[米]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来 INT * X [N] [M] 声明 X 是一个2-D指向整数数组,所以分配内存应该是那么容易,因为 X [I] [J] =新INT ,并如预期正常工作。现在,如果我改变声明:

As I see it int *x[n][m] declares x to be a 2-d array of pointers to integers, so allocating memory should be as easy as x[i][j] = new int and as expected it works fine. Now if I change the declaration to:

INT(* X)[N] [M]

X [I] [J] =新INT 不再起作用并导致编译错误。

x[i][j] = new int no longer works and results in a compilation error.

X =(INT(*)[N] [M])的malloc(sizeof的(INT [N] [M]))然而编译。从我已运行了几个测试,内存分配后,不同的报关/分配组合似乎并不影响存储在变量的值。我缺少的东西吗?所以我的问题是,有* X [N] [M]和INT(* X)[M] INT之间的差异[N]。如何为int(* X)[N] [M]存储在内存中?

x = (int(*)[n][m]) malloc (sizeof(int[n][m])) however compiles. From the few tests that I have run, after the memory allocation, the different declaration/allocation combination doesn't seem to effect the values stored in the variable. Am I missing something? So my question is, Is there a difference between int *x[n][m] and int (*x)[m][n]. How is int (*x)[n][m] stored in memory?

推荐答案

为int *一个[N] [M] 是指针的二维数组 INT

INT(* P)[N] [M] 是一个指向 INT 的二维数组S(这是你采取的地址获取类型的INT [n] [M] )。

int (*p)[n][m] is a pointer to a two dimensional array of ints (it is the type you get by taking the address of int[n][m]).

在这两种情况下, N M 必须编译时间常数,否则声明是不合法的C ++(但在C)。你的编译器可能有一个扩展,允许它,虽然。

In both cases, n and m need to be compile time constants, otherwise the declarations are not legal in C++ (but are in C). Your compiler might have an extension to allow it, though.

首先可以用来模拟一个三维阵列。我说模仿的,因为它不会与连续的存储适当的阵列和类型是摆在首位的不同。在每个 A 您可以存储地址到整数数组的第一个元素的元素。每个可以具有不同的尺寸和动态分配。您可以将存储指向一个单一的(可能是堆栈中分配)整了。

First one can be used to simulate a three dimensional array. I say simulate, because it would not be a proper array with contiguous storage and the types are different in the first place. In each of the elements of a you can store the address to the first element of an array of integers. Each could have a different size and be allocated dynamically. You can store a pointer to a single (possibly stack allocated) integer, too.

int i = 0;
int a1[2] = {};

int* a2[2][2];
a2[0][0] = a1;  // array to pointer decay here
a2[0][1] = new int[42];
a2[1][0] = new int[84];
a2[1][1] = &i;

P 可以指向一个二维数组或其数组:

p can point to a single 2d array or an array thereof:

int arr[2][3];
int (*p1)[2][3] = &arr;  // arr decays to int(*)[3], so we need to take the address
int (*p2)[2][3] = new int[42][2][3]; // allocate 42 arrays dynamically

这篇关于是什么INT之间的差* X [n]的[米]和INT(* X)[n]的[米]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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