首页 文章

C初学者 - 将char *数组复制到另一个char *数组

提问于
浏览
0

我一直在挣扎这个愚蠢的时间 . 基本上,我需要将一个char指针数组复制到另一个char指针数组 .

现在,我有这个功能:

void copyArray(char *source[], char *destination[]) {
    int i = 0;

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
}

这导致分段错误 . 有人可以帮忙吗?

谢谢!

编辑:示例程序

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

// Copy the contents of one array into another
void copyArray(char *source[], char *destination[]){
    // printf("In copy array");
    int i = 0;

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
}

void addToHistory(char *history[][40], char *args[]){
    int i;
    for(i = 1; i < 10; i++){
        copyArray(history[i], history[i-1]);
    }
    i = 0;
    copyArray(args, history[0]);
}

int main(void){
    char *history[10][40];
    char *args[40];

    history[0][0] = NULL;

    args[0] = "ls";
    args[1] = NULL;

    addToHistory(history, args);
}

3 回答

  • 0
    • 确保 source 数组中的最后一个元素是 NULL ,然后再将其传递给 copyArray .

    • copyArray 中,放置 while 而不是 do ,并增加循环的 i at the end .

    取而代之的是,你可以简单地在功能 copyArray 中将 i++ 更改为 ++i .

    但如果传递给此函数的 source 数组中的第一个元素是 NULL ,它将崩溃 .

  • 1

    我认为你有一个错误的错误:

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
                   ^^^
    

    在使用它之后检查是否 was 为NULL,然后结束循环 . 尝试替换它

    } while (source[++i] != NULL);           // or while (source[++i]), for short
    

    您可以尝试在每次迭代后记录一条短消息,以查看代码出错的位置 .

    编辑:你有没有理由使用 memcpy() (不会复制终止 '\0' )而不是 strcpy() (将会)?

    (注意@wildplasser:我相信 strdup() 可能不是标准C) .

  • 0
    void copyArray(char *source[], char *destination[]) {
    
        while ((*destiantion = *source)) {
            *destination++ = strdup( *source++ );
        }
    }
    

    BTW:将目的地作为第一个参数是常见的,就像在 strcpy() 中一样

    void copyArray(char *destination[], char *source[]) { ... }
    

相关问题