不匹配操作符+ 2D字符串数组指针表示法



我正在努力熟悉指针,所以我正在编写一个代码,其中有一个指向2d数组的指针。

这是我在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')|

我想我是按照书上的指示访问指针的,所以我不确定我在这里做错了什么。

谢谢。

让我们分解这行代码:

*(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!

所以看起来你在解引用一个2d数组。通常,您只需这样做:

board[row][col]

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

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

因此,我们可以取一个指向开始的指针,并将其视为一块连续的内存。但是我们如何找到正确的指针呢?好吧,假设我们有以下信息(我们确实有):

row, col, num_rows, num_cols

从2d数组索引中获取1d指针的常见方法如下:

row * num_col + col

作为练习,你应该在纸上写一个小的2d数组,并理解它是如何工作的。所以你可以创建一个函数,像这样:

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

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

最新更新