0

我正在编写一个命令行实用程序,但我找不到存储命令和参数的方法。到目前为止,我有以下内容,但出现分段错误:

int main(void)
{
    char *command;
    char *args[MAX_LINE/2 + 1]; 
    int should_run = 1;

    do{
         cout << "cmd> ";
         int counter = 0;
         while(cin >> command) {
             strcpy(args[counter],command);
             counter++;
         }
        cout << args[0] << "\n";
    }  
}
4

3 回答 3

4

您会遇到分段错误,因为:

cin >> command

尝试写入未初始化的内存。由于这是 C++,你应该这样做:

std::string command;

代替:

char * command;

同样对于args. 然后你可以做args[counter] = command而不是使用strcpy(). 对于额外的点,dostd::vector<std::string> args而不是使用数组,而args.push_back(command)不是args[counter] = command.

例如:

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::string command;
    std::vector<std::string> args;

    std::cout << "cmd> ";
    while( std::cin >> command ) {
        args.push_back(command);
    }

    int i = 0;
    for ( auto a : args ) {
        std::cout << "Arg " << i++ << " is " << a << std::endl;
    }

    return 0;
}

输出:

paul@local:~/src/cpp/scratch$ ./args
cmd> test this command
Arg 0 is test
Arg 1 is this
Arg 2 is command
paul@local:~/src/cpp/scratch$
于 2013-10-20T21:51:57.653 回答
2

一个常见的误解是它char *会在 C 或 C++ 中发挥特殊作用,主要是因为这是合法的:

char const * foo = "String";

实际上,char *它仍然只是一个指向 char 的指针,因此您需要先分配内存,然后才能为其分配字符串文字。您的代码中有两次此问题:

char * command;
std::cin >> command;

char * arr[N];
std::strcpy(arr[k], command);

在 C++ 中,您应该为此使用std::string和之类的容器。std::vector<std::string>如果您坚持使用 char 数组,则可以确定静态最大长度:

char command[MAX_LENGTH];
char args[N][MAX_LENGTH];

或动态使用new[]

char * command = new char[MAX_LENGTH];
char * args[N];
for(unsigned k = 0; k < N; ++k) args[k] = new char[MAX_LENGTH];

但是你必须记住也要释放该内存:

delete[] command;
for(unsigned k = 0; k < N; ++k) delete[] args[k];

因此,除非您有充分的理由不这样做,否则您应该更喜欢自动存储持续时间,因为您也应该有充分的理由不使用容器。

于 2013-10-20T22:02:06.710 回答
0

这个说法

while(cin >> command)

是无效的。首先,变量命令没有初始化,其次你必须分配内存,流 cin 可以在那里放置数据。使用字符数组(静态或动态分配)或使用类 std::string 输入数据。

于 2013-10-20T21:54:49.783 回答