|
|
发表于 2019-12-10 10:53:42
|
显示全部楼层
本楼为最佳答案
本帖最后由 jackz007 于 2019-12-10 10:55 编辑
你的问题出在,matrix 只是函数 int* gen(int N, int M) 的一个局部变量,其生存期只是在方法函数 gen() 的运行期间,一旦方法调用结束,局部变量 matrix 所占用的内存会被立即释放,供其它变量使用。就是说,在 gen() 以外,matrix 将不复存在。
- #include<iostream>
- using namespace std;
- class tes
- {
- public:
- int matrix[2][3] = {2} ;
- void gen(void)
- {
- for(int i = 0; i < 2; i++)
- {
- for(int j = 0; j < 3 ; j++)
- {
- matrix[i][j] = i * 2 + j ;
- }
- }
- }
- void show(void)
- {
- for(int i = 0; i < 2; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- cout << matrix[i][j] << " ";
- }
- cout << "\n" << endl ;
- }
- }
- };
- main(void)
- {
- tes t ;
- t.gen() ;
- t.show() ;
- }
复制代码
编译、运行实况:
- C:\Bin>g++ -o x x.cpp
- C:\Bin>x
- 0 1 2
- 2 3 4
- C:\Bin>
复制代码 |
|