【发布时间】: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]是什么意思? -
这个问题似乎离题了,因为它缺乏对所用语言的最低限度的了解。