题目描述:
Write a function that takes two int arguments,rows and columns. This function returns a pointer to a dynamicallyallocated two-dimensional array of float. As a hint, the first call tonew is: new float[rows][]. This must be followed by multiple callsto new in order to create all the storage for the rows. Write asecond function that takes this “matrix” and frees the storage usingdelete. Now convert the code into a struct calledmatrix.
大意是写一个函数:开辟一个float型的二维数组内存空间,并返回指向这个二维数组的指针
关于二维数组指针的详细解释,请参考这篇二维数组指针
#include<iostream>
//返回类型为 指向二维数组的指针
float** fun(int r, int c){
float **m = new float*[r]; //m为指向r个float型指针的指针
for(int i=0; i<r; i++){
m[i] = new float[c]; //m[i]是一个指向一维数组的指针
}
return m;
}
int main(){
int raw=5, column=4;
float z=0.1;
float **matrix = fun(raw, column);
for(int i=0; i<raw; i++){
for(int j=0; j<column; j++){
matrix[i][j]=z;
z+=1;
}
}
for(int i=0; i<raw; i++){
for(int j=0; j<column; j++){
std::cout << matrix[i][j] << std::endl;
}
}
}
动态二维浮点数矩阵的C++实现
本文介绍如何使用C++编写一个函数来创建并返回指向动态分配的二维浮点数数组的指针。包括如何遍历矩阵并初始化元素。
7587

被折叠的 条评论
为什么被折叠?



