【发布时间】:2017-09-15 09:13:50
【问题描述】:
我需要创建一个计算矩阵外部元素的程序。矩阵应由用户设置。 我的想法是创建程序的第一部分,用户可以在其中编写矩阵的元素,然后将该矩阵提供给将内部元素设置为 0 的函数,然后将其返回给 main() 然后启动另一个计算所有元素总和的函数。 问题是我无法将在主 {} 中声明的矩阵传递给函数。 我几乎可以肯定我需要使用指针,但是我不知道在这种情况下如何使用它们......你能帮忙吗? 这就是我目前写的代码:
#include <iostream>
#define MAX 10
using namespace std;
int zeroMatrix (int mat [][10], int, int);
int main()
{ //ask the user the number of rows and columns of the matrix.
int rows,cols;
cout << "please insert the number of rows: ";
cin >> rows;
cout << "insert the number of columns: ";
cin >> cols;
//accepting values
int matrix [rows] [cols];
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
cout <<"insert the element A(" << i <<","<< j << ") of the matrix " ;
cin >> matrix[i][j];
}
}
zeroMatrix (matrix [rows][cols]);
}
//change the previous matrix into a new matrix with the internal elements = 0
int zeroMatrix (int mat [][10], int rows, int cols )
{
for (int i=1; i<rows-1; i++)
{ for (int j=1; j<cols-1 ; j++)
{
mat[i][j] = 0;
}
}
}
【问题讨论】:
-
一个明确的问题,一个可能的问题:C++ 没有variable-length arrays。使用
std::vector代替可移植性。而在zeroMatrix中,为什么循环以索引1开始并以比大小小一结束? -
顺便问一下,你在问什么?错误地调用
zeroMatrix应该得到的构建错误?还有什么? -
它从 1 开始,因为它必须改变矩阵的内部元素。所以从 1 开始到行 -1 它只改变内部。正确的?无论如何,我要求使用指针更正此代码。我无法将 main 中的矩阵传递给函数。
-
@LuigiRusso 不要在 C++ 中使用原始数组和原始指针。不如按照建议使用
std::vector,或者创建自己的Matrix课程,让您的生活更轻松。 -
@user0042 谢谢你的建议,我不知道什么是 std::vector。您能否给我一个链接以更好地理解它以及如何使用它的一些示例?我们会非常感谢谢谢你
标签: c++ function pointers matrix sum