简体   繁体   English

如何清除c中的字符指针数组?

[英]How to clear a character pointer array in c ?

I am trying to implement a basic Unix Shell in C. My program stores the user's commands in an char ** args. 我试图在C中实现基本的Unix Shell。我的程序将用户的命令存储在char ** args中。 Here is my problem : 这是我的问题:

When I ask the user for a command, ex ls , ls is stored in args[0]. 当我询问用户命令时,ex ls,ls存储在args [0]中。 Then I fork a child process and execute the command using execvp. 然后,我派生一个子进程,并使用execvp执行命令。 Now the next time the user enters another command, say ls again, its stored at args[1]. 现在,下一次用户输入另一个命令时,再次说ls,它存储在args [1]中。 So I cant execute this command using execvp. 所以我不能使用execvp执行此命令。

I don't want to iterate through the array looking for ls or for any other arguements because then the program will execute random arguments. 我不想遍历数组查找ls或其他任何争论,因为这样程序将执行随机参数。

I need a way to empty my args so that I can rewrite args[1]. 我需要一种清空args的方法,以便可以重写args [1]。

int main() {
    pid_t childPro;
    pid_t parentPro;
    int i,r,argCount,status,pipeCount,changeOut;
    char **args;

    while(1) {
        argCount=0; 
        printf("davedShell$ "); 
        args = getln(); 

if(argCount>=1) {
    //Creating a child process through fork 
    childPro =fork (); 

    if(childPro==0){
        printf("Child Process: %d successfully created\n",(int) getpid());
        execvp(args[0],args);  
    }
    else if (childPro == -1) {
        printf("Fork Failed- Exiting"); 
    exit(1); 
    }
    parentPro = wait(&status);
    }

If you understood Getln() you could answer your own question, why not Getln(&args)? 如果您了解Getln(),则可以回答自己的问题,为什么不选择Getln(&args)? where is the memory allocated for args?. 为args分配的内存在哪里? allocating memory for args within function and returning a pointer to memory has to be handled correctly other wise you may get pointer to stack or registers depending on target architecture 在函数中为args分配内存并返回指向内存的指针必须正确处理,否则,您可能会根据目标体系结构获取指向堆栈或寄存器的指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM