c - 指向数组的指针的表示是什么?

标签 c arrays pointers multidimensional-array

我刚刚遇到这个处理多维数组的程序。虽然我已经了解了它的要点,但有一个特殊的符号我不确定。

这个想法是将指针传递给多维数组的列,因为 2-Dim 数组不需要您提及 2D 矩阵中的行数。因此,指向 2D 矩阵列的指针 pm 被传递为: int (*pm)[COLUMN]

这是完整的程序:

#include<stdio.h>
#include<stdlib.h>

const int ROW  = 2;
const int COL=3;

void fill_array(int (*pm)[COL], int row);
void display_array(int m[][COL], int row);

int main(int argc, char const *argv[])
{
    /* code */

    int i,j;
    int m[ROW][COL];

    //CALL function to enter elements
    fill_array(m,ROW);

    //display
    display_array(m,ROW);
    return 0;
}

void fill_array(int (*pm)[COL], int row)
{
    int i,j;

    printf("Please fill the array's content: \n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<COL;j++)
        {
            printf("\n m[%d][%d]: ",i,j);
            scanf("%d", &pm[i][j]);
        }
    }
}

void display_array(int m[][COL], int row)
{
    int i,j;

    printf("\n Array's contents: \n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<COL;j++)
        {
            printf("%d\t", m[i][j]);
        }

        printf("\n");
    }
}

我不确定指向数组的指针的表示形式。我的意思是我不熟悉这种将指针附加到数组的表示法。有人可以解释一下吗?

非常感谢!

最佳答案

当数组按值传递给函数时,它会转换为指向其第一个元素的指针。根据 C 标准(6.3.2.1 左值、数组和函数指示符)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

如果你传递这个数组

int m[ROW][COL];

一个函数,它被转换为指向其第一个元素的指针,该元素又是一个 int[COL] 类型的数组。指向该数组的指针看起来像

int ( * )[COL]

如果取消引用该指针,您将获得 int[COL] 类型的一维数组

例如,如果您声明了一个指向一维数组的指针,例如

int ( *pm )[COL]

然后表达式

*pm

类型为int[COL]

表达式 *pm 等价于 pm[0] 由于 pm[0] 是一个数组,那么您可以应用下标运算符 a第二次pm[0][0],将得到二维数组的第一个int类型的元素。

关于c - 指向数组的指针的表示是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26927563/

相关文章:

c - 指向结构体的指针

c++ - 在 malloc() 之后初始化结构体中的 ref-to-ptr

arrays - 从不兼容的指针类型传递 'functionName'的参数1

c - 如何在物理内存中指定变量位置?

java - JTextPane 将值从数组打印到 Java Swing 应用程序时出现问题

javascript - javascript中for循环内部回调函数所需的示例

php - 如何使用无数行查询

c++ - 为什么我必须向 poco 的某些方法提供指针而不是 SharedPtr

c - Pthreads:我的并行代码在达到一定数量后不会将线程传递到函数中

在 C 中使用 strtoull() 转换为 long long int