【问题标题】:Is there a way to run a loop with the help of pointers only and access every array index?有没有办法仅在指针的帮助下运行循环并访问每个数组索引?
【发布时间】:2023-02-23 02:23:29
【问题描述】:

我想运行一个循环并借助指针访问二维数组的每个索引,不允许使用下标运算符。实际上我想从文件中分配一个二维矩阵,不允许使用下标运算符和整数迭代器我必须借助指针访问循环

实际上我无法在指针的帮助下想出运行循环的逻辑所以任何人都可以给我一个例子或说明使用它的语法

【问题讨论】:

  • 你用两种不同的语言标记了这个问题。你问的是哪一个?
  • 你知道a[x]*(a+x)是一样的吗?
  • 我取决于你是否有一个连续的二维矩阵或一个指向一维数组的指针数组。请阅读How to Askminimal reproducible example,因为代码比文本描述更清晰。
  • 您忘记发布解决此问题的尝试。
  • 和下标运算符不允许使用-- 你知道a[i]*(a + i)是一样的吗?那么不使用下标运算符的原因是什么?是为了降低代码的可读性吗?

标签: c++ c loops pointers multidimensional-array


【解决方案1】:

没有指针的解决方案,使用 C++。 实际上,您应该避免使用指针来访问数组。 我知道你的老师在问什么,但他没有教 应该使用 C++。

// show this to your teacher
// using pointers to access arrays are an
// endless source of bugs. (for 2D arrays doubly so)
// - out of bound access (pointers loose size information of the data)
// - memory leaks (not clear who owns the memory the pointers point to)
// - lack of abstraction (too much how, too little what) so
//   unclear WHAT code is doing
// use std::vector, no need for pointers at all


#include <iostream>
#include <vector>

int main()
{
    
    std::vector<std::vector<int>> matrix
    { {
        {11,12,13},
        {21,22,23},
        {31,32,33}
    }};

    https://en.cppreference.com/w/cpp/language/range-for
    for (const auto& row : matrix) // loop over each row
    {
        for (const auto& value : row) // loop over each value
        {
            std::cout << value << " ";
        }
        std::cout << "
";
    }

    return 0;
}

指针解决方案:如果你有一个指向二维数组的指针,那么所有内存都是连续的,你可以像这样遍历它

int* ptr= &values[0][0];

for (std::size_t row = 0ul; row < 3; ++row )
{
    for (std::size_t col = 0ul; col < 3; ++col)
    {
        std::cout << *ptr << " ";
        ptr++;
    }
    std::cout << "
";
}

return 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多