【发布时间】:2017-03-16 23:17:59
【问题描述】:
我正在尝试解析std::string,将其拆分,然后将其存储在二维字符数组中。该数组的第一行将包含总行数。
我在getC_strings() 函数内动态分配数组,当我打印它时,我得到了预期的结果。但是,当我再次从 main() 打印时,我得到了第 0、2 行的垃圾。我做错了什么?
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
using namespace std;
/**
*
* @param input a string separated by spaces
* @param numArgs_ an int
* @param cargs a const char ** something. Pass it by its address aka &something.
*/
static inline void getC_strings(const std::string & input, int & numArgs_, const char *** cargs) {
std::vector<std::string> args;
boost::split(args, input, boost::is_any_of(" "), boost::token_compress_on);
numArgs_ = int(args.size());
*cargs = new const char* [numArgs_ + 1];
// store the number of rows at the first row
(*cargs)[0] = new char[to_string(numArgs_).size()];
(*cargs)[0] = to_string(numArgs_).c_str();
// write the characters from the vector per row
int ind = 0;
for(auto const &v:args) {
ind++;
(*cargs)[ind] = new char [int(v.size())];
if((*cargs)[ind] == NULL) std::cout << "OUT OF MEMORY! " << std::endl;
(*cargs)[ind] = const_cast<char*>(v.c_str());
}
for(int i = 0; i < numArgs_; ++i) {
std::cout << i << " " << (*cargs)[i] << std::endl;
}
}
int main () {
string arg = "test ./MyDirectoryName/OPQ_Arksoatn.txt 1 SOMETHING 1 2 3 4 5 6 7";
int numCargs = 0;
const char ** cargs;
getC_strings(arg, numCargs, &cargs);
cout << " ==============================================" << endl;
for(int i = 0; i < numCargs; ++i) {
std::cout << i << " " << cargs[i] << std::endl;
}
return 0;
}
输出:
0 11
1 test
2 ./MyDirectoryName/OPQ_Arksoatn.txt
3 1
4 SOMETHING
5 1
6 2
7 3
8 4
9 5
10 6
==============================================
0 ��`
1 test
2 `��
3 1
4 SOMETHING
5 1
6 2
7 3
8 4
9 5
10 6
【问题讨论】:
-
默认的
new运算符永远不会返回 null - 如果失败,它们会抛出异常。不要检查空结果。 -
你为什么在循环的乞求时增加
ind?要跳过数组的第一位吗? -
是的,在第一行我只想存储行数。
-
您的函数存在内存泄漏。你为什么要使用
new?为什么不使用std::vector? -
我正在与期望 const char ** 作为输入参数的旧代码交互