c++ - 如何在指针表示法和数组表示法中循环遍历二维数组

标签 c++ arrays loops pointers

我是 C++ 的新手,所以我想问一个简单的问题,但我似乎找不到答案。 我正在尝试编写一个函数来打印二维整数数组的所有元素并打印其内容。我正在尝试使用指针表示法使用数组表示法来做到这一点。我不知道要将什么发送到指针表示法的方法中。到目前为止,这是我的代码:

#include <iostream>
using namespace std;


void arrayNotation(int array[][4], int row){
    for (int i = 0; i < row; i++){
        for (int j = 0; j < 4; j++){
            cout << array[i][j];
        }
        cout << "\n";
    }
    cin.get();
}
void pointerNotation(){//i dont know what to send it
    for (int i = 0; i<4; i++){
        for (int j = 0; j<4; j++){
            cout << (*(*(array + i) + j));
        }
    }

}
int main(){     
    int array[2][4] = { { 467, 223, 189, 100 }, { 222, 561, 489, 650 } };
    arrayNotation(array, 2);
    pointerNotation();//how do you send it in to be pointer notation?

    return 0;
}

谢谢!

最佳答案

你需要的是

void pointerNotation(int (*array)[4]) // pass pointer to array-of-4 ints

但上面的内容实际上与 int array[][4] 相同,因为后者只是语法糖。

注意你不能这样做

void pointerNotation(int**)

因为 int[][4] 不会衰减到 int**。后者更灵活,前者只是一个指向 arrays-of-4-ints 的指针。

关于c++ - 如何在指针表示法和数组表示法中循环遍历二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29957660/

相关文章:

c++ - 我的 C++ 游戏架构

c++ - 使用双包装类进行位操作(C++,clang)修复性能下降

JavaScript:使用 forEach 查看数组是否包含特定数字值

arrays - Julia 代码优化 : is this the time to use SIMD?

javascript - 迭代数组并合并两个数组

c++ - FLTK 1.4 小部件位置 w.r.t. X11 根窗口?

c++ - 变长数组 : How to create a buffer with variable size in C++

javascript - 在 MVC 中将 2D 对象数组 C# 转换为 Javascript

delphi - Delphi ListView 中删除重复项

c++ - 我正在尝试创建一个类 vector ,然后用 for 循环命名每个类