【问题标题】:How can I print out an int* which I am accessing using [rows][cols] indexing?如何打印出我正在使用 [rows][cols] 索引访问的 int*?
【发布时间】:2014-01-20 14:37:45
【问题描述】:

我在 printf("%d ", arr[rows][cols]); 上得到一个编译错误符合编译器错误:

//error C2109: subscript requires array or pointer type

我想要按列排列的便利。最简单的访问方式是什么?

#include <stdio.h>

void print_matrix(int* arr, int numrows, int numcolumns) {
    for(int rows = 0; rows < numrows; ++rows) {
        for(int cols = 0; cols < numcolumns; ++cols)
            printf("%d ", arr[rows][cols]);   //error C2109: subscript requires array or pointer type

        printf("\n");
    }
}

int main() {

    const int rows = 3;
    const int cols = 2;
    int arr[rows][cols] = { {1,2}, {3,4}, {5,6} };

    int* p = &arr[0][0];

    print_matrix(p, rows, cols);

    return 0;
}

更新:

为了完整一点,我考虑了H2C03的评论,我应该更彻底地考虑一下。以下是实现相同目的的另一种方法,并且更简单,因为该函数采用简单的指针。

#include <stdio.h>

void print_matrix(int* arr, int rows, int cols) {
    int row, col;
    for( row = 0; row < rows; ++row) {
        for(col = 0; col < cols; ++col)
            printf("%d ", *(arr + row * cols + col));  

        printf("\n");
    }
}

void print_transpose(int* arr, int rows, int cols) {
    int row, col;
    for(row = 0; row < cols; ++row) {
        for( col = 0; col < rows; ++col)
            printf("%d ", *(arr + col * cols + row));  

        printf("\n");
    } 
}

int main() {

    const int rows = 3;
    const int cols = 2;
    int arr[3][2] = { {1,2}, {3,4}, {5,6} };
    int* p = arr;
    printf("matrix:\n");
    print_matrix(p, rows, cols);
    printf("transposed:\n");
    print_transpose(p, rows, cols);
    return 0;
}

【问题讨论】:

  • arr[rows * numcolumns + cols]...你有没有想过arr[rows][cols]是什么意思?
  • 这个问题似乎离题了,因为它缺乏对所用语言的最低限度的了解。

标签: c multidimensional-array


【解决方案1】:

需要将指针作为二维数组指针传递:

void print_matrix(size_t numrows, size_t numcolumns, int (* arr)[numcolumns]);

并传递为

print_matrix(rows, cols, arr);

【讨论】:

  • 不,他不需要。
  • @H2CO3 他不需要,但这是最简单、最方便的方法。
  • 显然,OP 想要手动解码行主要格式。我敢打赌这是一种锻炼。
  • @H2CO3 我引用了 OP:我想要按列排列的便利。
  • 谁在否决这个答案或试图删除它?我倾向于对这个问题有相同的解释:“如何将矩阵的二维结构传递给函数?”
【解决方案2】:

由于p 是指向arr 的第一个元素的指针,即p = &amp;arr[0][0],如果我们取消引用p,我们会得到&amp;arr[0][0] 的值。现在arr 是函数print_matrix 中指针p 的副本,因此如果我们取消引用arr,我们会得到arr[0][0] 的值。即*arr 给出arr[0][0]arr[rows][cols] 的计算结果为*(*(arr+rows) + cols)。这是一个问题,因为*(arr+rows) 给出了一个不能再次取消引用的值。我建议一个更简单的解决方案:

void print_matrix(int* arr, int numrows, int numcolumns) 
{
int totalelements = numrows * numcolumns, i ; 

    for(i = 0; i < totalelements; ++i) 
    {
        printf("%d\t ", arr[i]);  
        if((i+1) % numcolumns == 0)
          printf("\n");
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 2021-07-10
    • 2013-10-27
    相关资源
    最近更新 更多