如何为字符串数组实例变量动态分配空间? [英] How do you dynamically allocate space for a string array instance variable?
问题描述
我正在尝试使用c ++创建一个简单的shell程序。我有一个带有实例变量的CommandLine类,用于参数数量和这些参数的数组。
I'm trying to create a simple shell program using c++. I have a CommandLine class with instance variables for the number of arguments and an array of those arguments.
private:
int argc;
char *argv[];
这是在CommandLine类中定义构造函数的代码:
Here is the code for the definition of my constructor in my CommandLine class:
CommandLine::CommandLine(istream& in) {
string cmd;
getline(in, cmd);
vector<string> args;
string arg;
istringstream iss(cmd);
while( iss >> arg ) args.push_back(arg);
argc = args.size();
argv = (char*) malloc(argc*sizeof(argv));
}
当我尝试编译时,出现以下错误消息:
When I try to compile, I get this error message:
CommandLine.cpp:在构造函数'CommandLine :: CommandLine(std :: istream&)'中:
CommandLine.cpp:29:41:错误:分配的类型不兼容将'char *'更改为'char * [0]'
CommandLine.cpp: In constructor ‘CommandLine::CommandLine(std::istream&)’: CommandLine.cpp:29:41: error: incompatible types in assignment of ‘char*’ to ‘char* [0]’
推荐答案
将成员定义从以下位置更改:
Change your member definition from:
char * argv [];
to
char ** argv;
对于您的任务,它们将在功能上兼容。然后,以这种方式分配空间:
For your task, they will be functionally compatible. Then, allocate space this way:
argc = args.size();
argv = (char**)malloc(argc * sizeof(char*));
if(!args.empty())
{
for(int n = 0; n < argc; ++n)
{
const string& src = args[n];
char*& current = argv[n];
current = (char*)malloc((src.length() + 1) * sizeof(char));
memcpy(current, src.c_str(), (src.length() + 1) * sizeof(char));
}
}
但是,我不明白为什么您不能使用Member std :: vector< string>
类型的,因为您已经使用它来临时存储命令行参数。那将是更好的解决方案(并且更不容易出错)。
However, I do not understand why you cannot use member of type std::vector<string>
, since you already use it to temporarily store command line parameters. That would be much better solution (and less error-prone).
这篇关于如何为字符串数组实例变量动态分配空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!