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

标签 c arrays c89

我有一个类似的数组

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

我想在 outer 中获取第 n 个一维数组的指针/数组,类似于

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 */
}

当然这可以用指针数学来实现,但我觉得我忘记了一些语法。

最佳答案

对于指向数组的指针,声明inner作为指向 3 int 数组的指针

<罢工>
int (*inner)[3] = &outer[1]; 

<罢工>


如果你想要一个指向数组第一个元素的指针 outer[1]然后

int *inner = outer[1];  

会完成这项工作。你也可以这样做

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

关于c - 从二维数组中获取一维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35159005/

相关文章:

c - 通过声明字符类型T,在线判断显示运行时错误(SIGSEGV)

c - 有没有办法查明提供的密码是否与特定用户的实际密码匹配?

c - 错误: Expected expression before 'DATA/* : typedef struct DATA DATA */

c - void* 类型转换为 char* 的增量失败

c - #define 与用于寻址外围设备的枚举

c++ - 指针映射的数组下标运算符

ios - 使用 Swift 从数组中创建一个用换行符 (\n) 分隔的字符串

python - numpy loadtxt 单行/行作为列表

c - 使用 openmpi 初始化一个数组一次

c - 当我在 IF 体内声明变量时有什么缺点吗?