【问题标题】:No match for operator + 2D string array pointer notation运算符 + 2D 字符串数组指针表示法不匹配
【发布时间】:2021-10-24 08:18:36
【问题描述】:

我正在尝试熟悉指针,因此我正在编写一个代码,其中包含指向二维数组的指针。

这是我在 main 中的指针声明:

    string board[10][10];
    string *b = &board[0][0];

然后将指针传递给一个函数,我想使用指针将内容存储到该数组中。这就是问题所在。

void clearBoard(string *b) {
    cout << "   ";
    for (int i = 1; i < 11; i++) {
        cout << i << " ";
    } cout << endl;
    for (int r = 0; r < 10; r++) {
        cout << r + 1;
        if (r < 9) {
            cout << "  ";
        } else {
            cout << " ";
        }
        for (int c = 0; c < 10; c++) {
            *(*(b + r) + c) = "-";             <-- where problem occurs
            cout << *(*(b + r) + c) << " ";    <-- i can imagine there's a problem here to
            if (c == 9) {
                cout << endl;
            }
        }
    }
}

每当我尝试运行此程序时,都会出现:

error: no match for 'operator+' (operand types are 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} and 'int')|

我相信我试图访问我的书向我展示的指针,所以我不确定我在这里做错了什么。

谢谢。

【问题讨论】:

  • 我相信我试图访问我的书向我展示的指针, -- 我敢打赌你的书正在向你展示如何访问一维数组,而你'错误地尝试将其扩展到二维数组。我所知道的任何一本书都不会让 C++ 程序员以这种方式编写代码来操作 2D 数组。
  • 数组数组与指向指针的指针不同。而且您甚至没有指向指针的指针。还要了解对于任何指针p 和索引i,表达式*(p + i) 完全 等于p[i]。后者更容易阅读和理解。并且还解释了问题:*(*(b + r) + c)b[r][c] 相同,这没有意义。
  • 顺便说一句,你的代码中有很多magic numbers,还有很多单字母无法辨认的变量。使用更长的描述性名称。
  • @PaulMcKenzie 我确信我的书是针对 2D 数组的,这个网站也是如此:overiq.com/c-programming-101/pointers-and-2-d-arrays。可能是因为我使用的是字符串而不是导致问题的整数?我不确定。 (我的书以 long 为例)
  • 所有数组都可以衰减为指向其第一个元素的指针。对于“一维”数组,例如string some_strings[X] 然后它会衰减到 &amp;some_strings[0] 类型为 string*。你有一个“二维”数组(实际上是一个数组数组),它也会衰减到指向其第一个元素的指针:board[0]。但是在您的代码中,您有一个数组数组,因此指针类型 i 指向数组的指针(os string)string (*)[10]。这与您传递给 clearBoard 的参数非常不同. 您的变量b 的类型错误,无法指向数组数组。

标签: c++ arrays pointers


【解决方案1】:

让我们分解那行代码:

*(b + r) + c

     *(         // Dereferencing something, we will see what later
        b + r   // Adding an int to a string*, fine, we are moving where we point in 
                // the array
      ) + c     // Woops we dereferenced the above, it was a string*, so now it is a 
                // string. adding integer c to a string, can't be done!

所以看起来您正在取消引用二维数组。通常,你会这样做:

board[row][col]

但是由于您试图理解指针,因此您想使用 string*。所以让我们看看这个数组。它看起来像这样:

[[row1], [row2], ...]

所以我们可以将一个指向起点的指针视为一块连续的内存。但是我们如何找到正确的指针呢?好吧,假设我们有以下信息(我们确实这样做了):

row, col, num_rows, num_cols

从二维数组索引中获取一维指针的常用方法是这样的:

row * num_col + col

作为一个 excersize,你应该在纸上写一个小的二维数组并理解它是如何工作的。 所以你可以做一个函数,像这样:

string* getIndex(string* s, row, col, num_col) {
   return s + (row *num_col + col);
}

并使用它在字符串中获得正确的位置。

【讨论】:

    猜你喜欢
    • 2011-08-27
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2021-02-12
    • 2022-10-04
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多