Thinking in c++ exercise 4-26 關於二維數組指針

題目描述:

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;
		}
	}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章