在 C 中编程 Shell,传递给函数时消失 char**

Programming a Shell in C, Disappearing char** When Passed to Function

我只找到了几个这样的主题,并且 none 包含我能够理解的信息。我正在用 C 编写 shell,我觉得这应该很容易,但我的 C 编程不是很新鲜。我在传递双指针和内容消失时遇到问题

我觉得我在正确的轨道上,听起来它与初始化有关,但我已经尝试了一些东西,将指针设置为 NULL 只是为了确定。谢谢

void runProgram (char **cLine);
char **parse(char *str);

/*
 * 
 */
int main(int argc, char** argv) 
{
    char *cin = NULL;
    ssize_t buffer = 0;
    char **tempArgs = NULL;
    printf(">");

    while(1)
    {
        getline(&cin, &buffer, stdin);
        tempArgs = parse(cin);  //malloc, parse, and return
        printf("passing %s", tempArgs[0]);  //works just fine here, can see the string
        runProgram(tempArgs); //enter this function and array is lost
    }
    return (EXIT_SUCCESS);
}
char** parse( char* str )
{
    char *token = NULL;
    char tokens[256];
    char** args = malloc( 256 );    
    int i = 0;

    strcpy( tokens, str );

    args[i] = strtok( tokens, " " );

    while( args[i] )
    {

        i++;
        args[i] = strtok(NULL, " ");
    }
    args[i] = NULL;

    return args;
}

在调用此函数之前在 main 中可见

void runProgram (char **cLine)
{
   //function that calls fork and execvp
}

最简单的解决方法是在 parse() 函数中完全不使用 tokens

int main(void) 
{
    char  *buffer = NULL;
    size_t buflen = 0;
    char **tempArgs = NULL;

    printf("> ");

    while (getline(&buffer, &buflen, stdin) != -1)
    {
        tempArgs = parse(buffer);
        printf("passing %s", tempArgs[0]);
        runProgram(tempArgs);
        printf("> ");
        free(tempArgs);  // Free the space allocated by parse()
    }
    free(buffer);        // Free the space allocated by getline()
    return (EXIT_SUCCESS);
}

char **parse(char *str)
{
    char **args = malloc(256); 
    if (args == 0)
        …handle error appropriately…   
    int i = 0;

    args[i] = strtok(str, " ");

    // Bounds checking omitted
    while (args[i])
        args[++i] = strtok(NULL, " ");

    return args;
}

请注意,当循环终止时,数组已经以 null 终止,因此不需要额外的赋值(但安全总比遗憾好)。