我编写C++已经有一段时间了,我对这个代码示例有一些问题:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
string* data;
int current = 0;
void init(){
data = new string[6];
data[0] = "7 4 3";
data[1] = "8 11 12 16 17 18 20";
data[2] = "17 16 20 2 20 5 13";
data[3] = "17 8 8 16 12 15 13";
data[4] = "12 4 16 4 15 7 6";
data[5] = "8 14 2 11 17 12 8";
}
string getNext() {
if(current == 0){
init();
}
return data[current++];
}
void populate(int* target, int n){
target = new int[n];
string line = getNext();
stringstream ss(line);
for(int i=0; i<n; i++){
ss >> target[i];
cout << target[i] << endl;
}
// THIS WORKS FINE
for(int i=0; i<n; i++){
cout << "TARGET" << target[i] << endl;
}
}
int main() {
string line;
int n, s, e;
int* x, * a, * b, * c, *d;
line = getNext();
stringstream ss(line);
ss >> n >> s >> e;
cout << "N: " << n << " S: " << s << " E: " << e << endl;
populate(x, n);
// IMMEDIATE SEGMENTATION FAULT ON FIRST ITERATION
for (int i = 0; i < n; i++)
cout << x[i] << endl;
populate(a, n);
populate(b, n);
populate(c, n);
populate(d, n);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这个程序的最终形式中,它将需要用户输入,但是现在我用一个字符串数组模拟输入,我可以阅读,就像我从cin读取的那样.
我有几个整数数组指针,我将动态分配并用一行字符串输入填充每个.
我写了这个函数populate()来为我做这个,所以我没有太多重复的代码.
populate()似乎将数据加载到指定的指针中.我甚至可以在从函数返回之前将其打印出来.
但是,如果我尝试读取指针AFTER populate()返回,我会立即得到分段错误.知道为什么吗?一旦函数返回,引用是否会丢失?我是否必须以某种方式明确地将字符串块转换为int?我对此感到有点困惑.
GOT IT:已经有一段时间了.谢谢!
这是罪魁祸首:
void populate(int* target, int n){
target = new int[n];
...
Run Code Online (Sandbox Code Playgroud)
在这里,我们传递target的int*,则立即重新分配本地它分配的内存,和耦合到您在丢失通过的指针.x因此,内部仍然是单元化的,main并且访问它是未定义的行为.变更的类型target来int*&,它应该为你工作.您也可以使用int**并传递x的地址,但这需要对target您的函数内部进行大量更改.
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |