问题描述
尝试学习C ++并尝试对数组进行简单的练习。
Trying to learn C++ and working through a simple exercise on arrays.
基本上,我创建了一个多维数组,我想创建一个打印出值的函数。
Basically, I've created a multidimensional array and I want to create a function that prints out the values.
Main()中的注释for-loop工作正常,但是当我尝试将该for循环转换为函数时,它不起作用,对于我的生活,我看不出为什么。
The commented for-loop within Main() works fine, but when I try to turn that for-loop into a function, it doesn't work and for the life of me, I cannot see why.
#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++ inherits its syntax from C, and tries hard to maintain backward compatibility where the syntax matches. So passing arrays works just like C: the length information is lost.
然而,C ++提供了一种方法来自动传递长度信息,使用引用关系,C没有引用):
However, C++ does provide a way to automatically pass the length information, using a reference (no backward compatibility concerns, C has no references):
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;
}
}
演示:
这是一个避免复杂数组引用语法的变体:
Here's a variation that avoids the complicated array reference syntax: http://ideone.com/GVkxk
如果大小是动态的,则不能使用任一模板版本。你只需要知道C和C ++以行为主的顺序存储数组内容。
If the size is dynamic, you can't use either template version. You just need to know that C and C++ store array content in row-major order.
可变大小的代码:
这篇关于c ++错误:无效类型int int数组下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!