向量向量指针分配有一个简单的问题:
我试图在main
函数中初始化矢量指针的类中分配值并将其放入。它在test_class
中通过引用传递。现在,在test_class
方法test_function()
中分配了此向量指针的分配。在main
中,我应该获取指针的值,但是发现没有分配指针。
test_function(vector<vector<int*>>)
,可以正常工作。#include <iostream>
#include <vector>
using namespace std;
#define N 20
class test_class {
private:
vector<vector<int*>> a_class;
public:
test_class(vector<vector<int*>>& a) : a_class(a) {}
void test_function() {
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++) a_class[i][j] = new int[2];
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++) {
*(a_class[i][j] + 1) = i + j + 1;
*a_class[i][j] = i + j;
}
}
};
int main() {
vector<vector<int*>> a_main;
a_main.resize(N);
for(int i = 0; i < N; i++) a_main[i].resize(N);
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++) a_main[i][j] = nullptr;
test_class* obj = new test_class(a_main);
obj->test_function();
for(int i = 0; i < N; i++) {
cout << N << " \n";
for(int j = 0; j < N; j++)
cout << *(a_main[i][j]) << " " << *(a_main[i][j] + 1) << "\n";
}
return 0;
}
"test_func.cc" 50L, 826C
(gdb) run
Starting program:test_func.o
20
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400cad in main () at test_func.cc:46
46 cout<<*(a_main[i][j])<<" "<<*(a_main[i][j]+1)<< "\n";