为什么我们不能直接将2D数组的地址分配给指针? [英] Why can't we directly assign the address of a 2D array to a pointer?

查看:89
本文介绍了为什么我们不能直接将2D数组的地址分配给指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们不能直接将2D数组的地址分配给指针?

Why can't we directly assign the address of a 2D array to a pointer?

有什么方法可以在一行中分配它,而不借助 for 循环的帮助吗?

Is there any way we can assign it in a single line, not with the help of a for loop?

还有其他更好的方法吗?

Is there any other better approach?

// Array of 5 pointers to an array of 4 ints 

int (*Aop[5])[4];

for(int i = 0;i<5;i++) 
{
    Aop[i] = &arr2[i];  //Works fine
} 
 
//Why this doesn't work int 
int (*Aop[5])[4] = &arr2[5][4]

推荐答案

此声明

int (*Aop[5])[4];

不声明指针.它是一个由5个指向 int [4] 的一维数组的指针组成的数组的声明.

does not declare a pointer. It is a declaration of an array of 5 pointers to one-dimensional arrays of the the int[4].

数组没有赋值运算符.但是,您可以在其声明中对其进行初始化,例如

Arrays do not have the assignment operator. However you could initialize it in its declaration as for example

int (*Aop[5])[4] = { &arr2[0], &arr2[1], &arr2[2], &arr2[3], &arr2[4] };

int (*Aop[5])[4] = { arr2, arr2 + 1, arr2 + 2, arr2 + 3, arr2 + 4 };

这是一个演示程序.

#include <stdio.h>

int main(void) 
{
    enum { M = 5, N = 4 };
    
    int arr2[M][N] =
    {
        { 1, 1, 1, 1 },
        { 2, 2, 2, 2 },
        { 3, 3, 3, 3 },
        { 4, 4, 4, 4 },
        { 5, 5, 5, 5 }
    };
    
    int (*Aop[M])[N] = { arr2, arr2 + 1, arr2 + 2, arr2 + 3, arr2 + 4 };
    
    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            printf( "%d ", ( *Aop[i] )[j] );
        }
        putchar( '\n' );
    }
    
    return 0;
}

程序输出为

1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 
5 5 5 5

如果您需要声明指向数组 arr2 的指针,则应记住,数组指示符被隐式转换(很少有例外)指向指向其第一个元素的指针.数组 arr2 具有类型为 int [4] 的元素.因此,指向该类型对象的指针的类型将为 int(*)[4] .这样你就可以写

If you need to declare a pointer to the array arr2 then you should bear in mind that array designators are implicitly converted (with rare exceptions) to pointers to their first elements. The array arr2 has elements of the type int[4]. So a pointer to an object of this type will have the type int ( * )[4]. So you can write

int (*Aop )[4] = arr2;

这是另一个演示程序,该程序在for循环中使用指针输出数组 arr2 的元素.

Here is another demonstrative program that uses pointers in for loops to output elements of the array arr2.

#include <stdio.h>

int main(void) 
{
    enum { M = 5, N = 4 };
    
    int arr2[M][N] =
    {
        { 1, 1, 1, 1 },
        { 2, 2, 2, 2 },
        { 3, 3, 3, 3 },
        { 4, 4, 4, 4 },
        { 5, 5, 5, 5 }
    };
    
    int (*Aop )[N] = arr2;
    
    for ( int ( *p )[N] = Aop; p != Aop + M; ++p )
    {
        for ( int *q = *p; q != *p + N; ++q )
        {
            printf( "%d ", *q );
        }
        putchar( '\n' );
    }
    
    return 0;
}

再次显示程序输出

1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 
5 5 5 5

这篇关于为什么我们不能直接将2D数组的地址分配给指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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