尝试学习 C++ 并完成一个关于数组的简单练习。
基本上,我已经创建了一个多维数组,我想创建一个打印出值的函数。
Main() 中的注释 for 循环工作正常,但是当我尝试将该 for 循环转换为函数时,它不起作用,而且对于我来说,我不明白为什么。
#include <iostream>
using namespace std;
void printArray(int theArray[], int numberOfRows, int numberOfColumns);
int main()
{
int sally[2][3] = {{2,3,4},{8,9,10}};
printArray(sally,2,3);
// for(int rows = 0; rows < 2; rows++){
// for(int columns = 0; columns < 3; columns++){
// cout << sally[rows][columns] << " ";
// }
// cout << endl;
// }
}
void printArray(int theArray[], int numberOfRows, int numberOfColumns){
for(int x = 0; x < numberOfRows; x++){
for(int y = 0; y < numberOfColumns; y++){
cout << theArray[x][y] << " ";
}
cout << endl;
}
}
最佳答案
C++ 继承了 C 的语法,并努力在语法匹配的地方保持向后兼容性。所以传递数组就像 C 一样:长度信息丢失。
但是,C++ 确实提供了一种使用引用自动传递长度信息的方法(没有向后兼容性问题,C 没有引用):
template<int numberOfRows, int numberOfColumns>
void printArray(int (&theArray)[numberOfRows][numberOfColumns])
{
for(int x = 0; x < numberOfRows; x++){
for(int y = 0; y < numberOfColumns; y++){
cout << theArray[x][y] << " ";
}
cout << endl;
}
}
这是一个避免复杂数组引用语法的变体:http://ideone.com/GVkxk
如果大小是动态的,则不能使用任何一个模板版本。您只需要知道 C 和 C++ 以行优先顺序存储数组内容即可。
适用于可变大小的代码:http://ideone.com/kjHiR
关于C++ 错误 : invalid types 'int[int]' for array subscript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6165449/