简体   繁体   English

多维数组和指针寻址

[英]Multidimensional array and pointer addressing

#include <stdio.h>
int main(void)
{
  int x[2][3] =
  {
    {4, 5, 2},
    {7, 6, 9}
  };
  int (*p)[3] = &x[1];
  int (*q)[3] = x;
  printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  //7, 6, 9
  printf("%d %d\n", *q[0], *q[1]);  // 4, 7
  return 0;
}

x[0] ----> [4, 5, 2]. x [0] ----> [4,5,2]。

x[1] ----> [7, 6, 9] x [1] ----> [7,6,9]

so if p=X[1] , p[0]=7 , p[1]=6 and p[2]=9 , so the first printf is understandable. 因此,如果p=X[1]p[0]=7p[1]=6p[2]=9 ,则第一个printf是可以理解的。

For the second printf, x will be equal to the address first element of the array. 对于第二个printf, x将等于数组的地址第一个元素。 If *q[0] is 4, why is *q[1] 7, shouldn't it be 5? 如果* q [0]为4,为什么* q [1]为7,不应该为5? It skips a row. 它跳过一行。


Actual output from link: 链接的实际输出:

7 6 9
4 7

Compare these two lines: 比较这两行:

printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  //7, 6, 9
printf("%d %d\n", *q[0], *q[1]);  // 4, 7

In the first line you have dereferenced the pointer first and then accessing the index - in your second line you're missing the parenthesis. 在第一行中,您首先取消了对指针的引用,然后访问了索引-在第二行中,您缺少了括号。 Changing it to: 更改为:

  printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  // 7, 6, 9
  printf("%d %d %d\n", (*q)[0], (*q)[1]);  // 4, 5

Will output the values as you expect. 将按预期输出值。

it is pointing to the second array in x. 它指向x中的第二个数组。

If you want to get all elements of first row you can use something like this. 如果要获取第一行的所有元素,则可以使用类似这样的内容。

#include <stdio.h>
int main(void)
{
int x[2][3] =
{
{4, 5, 2},
{7, 6, 9}
};
int (*p)[3] = &x[1];
int (*q)[3] = x;
printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  //4, 5, 2
printf("%d %d %d\n", *q[0], q[0][1],q[0][2]);  // 4, 5,2
return 0;
}

Output you get is valid . 您得到的输出是有效的。

*q[1] is equivalent to q[1][0] . *q[1]等效于q[1][0] And therefore , value at that index is 7 which you get as output . 因此,该索引处的值为7 ,您可以将其作为输出获得。

To get 5 you can write like this q[0][1] or the other way to represent (*q)[1] . 要得到5您可以这样写q[0][1]或用另一种方式表示(*q)[1]

It's an operator precedence issue. 这是运算符优先级的问题。 [] has higher priority than unary * . []比一元*具有更高的优先级。 If [] is applied to an array pointer, it will perform pointer arithmetic by the same rules as for regular pointers. 如果将[]应用于数组指针,它将按照与常规指针相同的规则执行指针算术。

For any pointer type, ptr[i] equals *(ptr + i) , and ptr+i means "give me the address of ptr plus i*sizeof(*ptr) bytes. 对于任何指针类型, ptr[i]等于*(ptr + i) ,而ptr+i意思是“给我ptr的地址加上i*sizeof(*ptr)个字节。

So in your case q[1] means "give me the address of q + 1*sizeof(*q) , where the contents of q is an array of 3 integers. So you end up pointing at the beginning of the 2nd array. 因此,在您的情况下, q[1]意思是“给我q + 1*sizeof(*q) ,其中q的内容是3个整数的数组。因此,您最终指向第二个数组的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM