2014-01-22 102 views
0

我一直在努力与这一个愚蠢的长时间。 基本上,我需要将一个char指针数组复制到另一个char指针数组。C初学者 - 复制一个字符*数组到另一个字符*数组

现在,我具备的功能:

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); 
} 
+0

是你可以肯定,阵列源[]具有最终NULL值? – BRFennPocock

+0

您是否尝试过使用调试器? – 2014-01-22 17:53:08

+0

你能展示一个完整的(但很小的)示例程序来演示这个问题吗? – simonc

回答

1
  1. 确保source数组中的最后一个元素是NULL,你把它传递给copyArray之前。

  2. copyArray,把while代替do,并在循环结束仅增加i

代替上述所有的,你可以简单地在功能copyArray改变i++++i

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

0

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

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)。

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

    while ((*destiantion = *source)) { 
     *destination++ = strdup(*source++); 
    } 
} 

顺便说一句:常见的是使目的地的第一个参数,正如在strcpy()

void copyArray(char *destination[], char *source[]) { ... } 
相关问题