gpt4 book ai didi

shell - 无法将 ‘const char*’ 转换为 ‘char* const*’

转载 作者:行者123 更新时间:2023-12-01 13:01:35 25 4
gpt4 key购买 nike

我正在尝试实现一个 shell。我将创建一个 hist 数组来存储最后 10 个命令,我希望以后能够检索这些命令以便执行。因此,我试图找到一种方法,一旦我将所有命令行参数存储在该 hist 数组中,就可以将它们取回。

提供了一些代码,gettoks(),是一个获取和解析命令行输入的函数。函数 gettoks() 返回一个指向字符串的指针数组。每个字符串要么是包含字母、数字、. 和/的单词,要么是包含特殊字符之一的单个字符串:( ) < > | & ;

我知道我可以将 toks 传递给 execvp,以便在执行命令后立即执行命令,但是一旦它存储在二维字符串数组中,我将如何检索它?

我也明白指针和数组可以让我的生活更轻松,但我对它们还是不太熟悉!所以,我想知道我是否可以获得一些关于代码的反馈并解决“execvp(c[0] , c);”行的编译错误。

“错误:从‘char’到‘const char*’的无效转换 错误:无法将参数“2”的“const char*”转换为“char* const*”到“int execvp(const char*, char* const*)””

谢谢。

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <cstdlib>
#include <stdio.h>

using namespace std;

extern "C"
{
extern char **gettoks();
}

int main( int argc, char *argv[] )
{
// local variables
int ii;
char **toks;
int retval;
string tokenString;
string hist[11][2];

// initialize local variables
ii = 0;
toks = NULL;
retval = 0;
tokenString = "";

int m = 0; // command counter

for(int i = 0; i < 11; i++){ // initialize the hist array
for (int j = 0; j <2; j++){
hist[i][j]= "";
}
}

// main (infinite) loop
while( true )
{
// get arguments
toks = gettoks();

if( toks[0] != NULL ){ // if a command is entered
if ( m < 10){
m++; // increment the number of commands
for( ii=0; toks[ii] != NULL; ii++ ){ // add the command to the hist array
tokenString += toks[ii];
}
hist[m][0] = toks[0];
hist[m][1] = tokenString;
}
else if (m == 10){ // if the hist array is full
for( int k = 1; k < 10; k++ ){ // shift the commands in the hist array
for (int l = 0; l < 2; l++){
hist[k][l] = hist[k+1][l];
}
}
for( ii= 0; toks[ii] != NULL; ii++ ){ // add the new command to the hist array
tokenString += toks[ii];
}
hist[10][0] = toks[0];
hist[m][1] = tokenString;
}

}
for(int i = 1; i < 11; i++){// print the hist array
for (int j = 0; j <2; j++){
cout << hist[i][j] << "\t";
}
cout << endl;
}

tokenString = ""; // reset

const char * c = hist[1][1].c_str();
execvp(c[0] , c);


if( !strcmp( toks[0], "exit" ))
break;
}


// return to calling environment
return( retval );
}

最佳答案

execvp 旨在像这样使用:

char* cmd[] = { "sleep", "1", NULL };
execvp(cmd[0], cmd);

但是在您的代码中,您传递的是 c,这是一个常规的 C 字符串 (const char *)。您可以将 gettoks() 函数返回的数组直接与 execvp 一起使用。

关于shell - 无法将 ‘const char*’ 转换为 ‘char* const*’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com