题目描述:
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;
}
}
}