简体   繁体   English

从二维数组中获取一维数组

[英]Getting one-dimensional arrays from a two-dimensional array

I have an array like 我有一个类似的数组

int outer[4][3] = {
    { 1, 2, 3 },
    { 2, 3, 5 },
    { 1, 4, 9 },
    { 10, 20, 30 }
};

and I would like to get a pointer/array for the n-th one-dimensional array inside outer , something like 我想获得用于内的第n个一维数组的指针/阵列outer ,像

void foo () {
    printf("%d %d %d\n", outer[1][0], outer[1][1], outer[1][2]);
    int inner[3] = outer[1]; /* Is there some way to do this assignment? */
    printf("%d %d %d\n", inner[0], inner[1], inner[2]);
    /* so that this line gives the same output as the first */
}

Of course this is possible with pointer math, but I feel like there is some syntax for this that I've forgotten. 当然这可以通过指针数学来实现,但我觉得有一些我已经忘记的语法。

For pointer to array, declare inner as a pointer to an array of 3 int 对于指向数组的指针,将 inner声明为指向3 int数组的指针

 
 
 
  
  int (*inner)[3] = &outer[1];
 
  


If you want a pointer to first element of array outer[1] then 如果你想要一个指向数组outer[1]第一个元素的指针

int *inner = outer[1];  

will do the job. 会做的。 You can also do 你也可以

int *inner = &outer[1][0];

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

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