【发布时间】:2014-01-22 17:49:57
【问题描述】:
我已经为此苦苦挣扎了很长时间。 基本上,我需要将一个 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);
}
【问题讨论】:
-
你确定数组 source[] 有一个最终的 NULL 值吗?
-
您尝试过使用调试器吗?
-
你能展示一个完整的(但很小的)示例程序来演示这个问题吗?
-
出于我的目的,我知道 source 将以最终的 NULL 值结尾(这是我的程序中解析字符串的方式)。我正在开发一个简单的 shell 程序,并上传了一个小的测试代码 sn-p..
-
请检查你的qn的答案,这里:stackoverflow.com/questions/36565328/…
标签: c