将指针的值复制到另一个指针

Copying the value of a pointer to another pointer

我想将 char *command 中存储的值复制到 char *command_copy,因为我正在对 command 执行标记化,但仍想使用初始命令(即为什么我要创建一个副本)。问题是每次我尝试一些东西时,整个程序都会变得疯狂,我就是找不到从哪里开始或做什么。

这是我的代码:

int main(void)
{
    init_ui();
    hist_init(100);

    char *command;
    while (true) {
        signal(SIGINT, SIG_IGN);
        command = read_command();
        if (command == NULL) {
            break;
        }
        char *command_copy;
        command_copy = (char *) malloc(1000);
        memcpy(command_copy, command, sizeof(*command));
        char *args[4096];
        int tokens = 0;
        char *next_tok = command;
        char *curr_tok;
        while((curr_tok = next_token(&next_tok, " \t\n\r")) != NULL) {
            if(strncmp(curr_tok, "#", 1) == 0){
                break;
            }
            args[tokens++] = curr_tok;
        }
        args[tokens] = NULL;

        if(args[0] == NULL) {
            continue;
        }

        hist_add(command);

        int builtin_status = handle_builtins(tokens, args);
        if(builtin_status == 0) {
            continue;
        }

        pid_t child = fork();
        if(child == -1){
            perror("fork");
        }
        ...

我希望 hist_add() 函数采用 command_copy 而不是 command 因为 command 在代码中的那一点只是整个首字母的第一个单词命令,我希望 hist_add() 拥有整个(原始)命令。

read_command(无效):

char *read_command(void)
{
    if(scripting == true) {
        ssize_t read_sz = getline(&line, &line_sz, stdin);
        if(read_sz == -1){
            perror("getline");
            free(line);
            return NULL;
        }
        line[read_sz - 1] = '[=11=]';
        return line;
    }
    else {
        return readline(prompt_line());
    }
}

要复制 char* 字符串 - 只要该字符串正确 nul 终止 - 您可以使用 strdup function.这本质上是 mallocstrcpy.

的组合

所以,你可以使用这样的东西:

while (looping) {
    char* original = getstring();
    char* copy = strdup(original);
    // ...
    // do whatever you want with "original" - "copy" is left alone!
    //
    free(copy); // When you're done, free the copy
}

strdup 调用等效于以下内容:

    char* copy = malloc(strlen(original) + 1);
    strcpy(copy, original);