【发布时间】:2013-04-06 15:48:01
【问题描述】:
我有一个字符串块,比如“aaa\0bbbb\0ccccccc\0” 我想把它们变成一个字符串数组。 我尝试使用以下代码这样做:
void parsePath(char* pathString){
char *pathS = malloc(strlen(pathString));
strcpy(pathS, pathString);
printf(1,"33333\n");
pathCount = 0;
int i,charIndex;
printf(1,"44444\n");
for(i=0; i<strlen(pathString) ; i++){
if(pathS[i]=='\0')
{
char* ith = malloc(charIndex);
strcpy(ith,pathS+i-charIndex);
printf(1,"parsed string %s\n",ith);
exportPathList[pathCount] = ith;
pathCount++;
charIndex=0;
}
else{
charIndex++;
}
}
return;
}
exportPathList 是前面代码中定义的全局变量 char* exportPathList[32]; 使用该函数时 exportPathList[i] 包含垃圾。 我做错了什么?
【问题讨论】:
-
当你执行 strlen(pathString) 时,你只会得到第一个字符串的长度,而这就是 strcpy 将复制的所有内容。而且您永远不会记录“最后一个”字符串,因为您在 strlen 处停止,因此永远不会看到终止的 null。
-
直到你不知道该块包含多少个字符串,你才能做到。
-
您基本上需要通过其他方式知道输入字符串的长度。
-
您需要使用双空值终止您的输入字符串。否则,您将无法知道字符串数组的结束位置。