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

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

现在,我有这个function:

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  #include  #include  // 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); } 

  1. 在将其传递给copyArray之前,请确保source数组中的最后一个元素为NULL

  2. copyArray ,输入while不是do ,并仅循环结束时递增i

相反,所有上述内容,您只需在函数copyArray i++更改为++i copyArray

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

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

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

使用它之后检查我是否 NULL,然后结束循环。 尝试替换它

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

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

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

(注意@wildplasser:我认为strdup()可能不是标准的C)。

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

顺便说一句:将目标作为第一个参数是常见的,就像在strcpy()

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