gpt4 book ai didi

c - 我的 char vector 在每个位置保存相同的值

转载 作者:太空宇宙 更新时间:2023-11-04 12:09:12 24 4
gpt4 key购买 nike

我正在尝试在 Linux 中制作一个 shell。我需要保存用户键入的每个命令,当用户想查看历史记录时,我会向他显示最后 10 个命令。我正在使用 char* historial[10];但是当用户键入第二个命令时,它在 historial[0] 和 historial[1] 中保存的是同样的东西。所以如果我键入 10 个不同的命令,它会保存最后一个命令 10 次。我不知道我做错了什么。PS:我在 do while 中的条件都不工作。

int ejecutarCom(char* comando)
{ //executes the command
pid_t pid;
pid = fork();
int aux = 0;
if (pid < 0)
{
perror("Error");
return -1;
}
else if (pid == 0)
{
aux = execlp(comando, comando, NULL);
}
else
{
wait(NULL);
}
return aux;
}

char* historial[10]; //history vector
int cantidad = 0, tamano = 10; //quantity & size
void guardarEnHistorial(char* c)
{ //saves every command
if (cantidad < tamano)
{
historial[cantidad] = c;
}
if (cantidad == tamano)
{
cantidad = 0;
historial[cantidad] = c;
}
cantidad++;
}

void verHistorial()
{ //shows history
for (int i = 9; i >= 0; i--)
{
if (historial[0] == NULL)
break;
else if (historial[i] == NULL)
{
printf(" ");
}
else
printf("%i: %s\n", i, historial[i]);
}
}

int main()
{
char* comando = (char*) malloc(1024);
int x = 1;
do
{
printf("%s ", prompt);
fflush(stdout);
fgets(comando, sizeof(comando), stdin);
comando[strcspn(comando, "\n")] = '\0';
printf("%s\n", comando);
if (strcmp(comando, "hist") == 0)
{
verHistorial();
}
else
{
x = ejecutarCom(comando);
guardarEnHistorial(comando);
printf("%i\n", x);
}
} while (x != -1);

最佳答案

修改您的主要功能,如下所示。历史数组的每个位置都指向相同的内存位置,因此您在每个位置都获得相同的信息。您必须为每个命令分配内存,如下所示:-

int main(){
char* comando=(char*) malloc(1024);
int x=1;
do{
printf("%s ",prompt);
fflush (stdout);
fgets(comando,sizeof(comando),stdin);
comando[strcspn(comando, "\n")] = '\0';
printf("%s\n",comando);
if(strcmp(comando,"hist")==0){
verHistorial();}
else{
x=ejecutarCom(comando);
guardarEnHistorial(comando);
comando=(char*) malloc(1024);// You need to allocate memory to store
//each history records. Also consider whether you really need 1024 bytes of memory make it small
printf("%i\n",x);
}}while(x!=-1);

关于c - 我的 char vector 在每个位置保存相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527677/

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