我一直在努力与这一个愚蠢的长时间。 基本上,我需要将一个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);
}
是你可以肯定,阵列源[]具有最终NULL值? – BRFennPocock
您是否尝试过使用调试器? – 2014-01-22 17:53:08
你能展示一个完整的(但很小的)示例程序来演示这个问题吗? – simonc