2014-01-22 46 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[]) { ... } 
相關問題