[英]splitting a long dynamic string into an array of strings in c
我對 C 很陌生,可以弄清楚為什么這個 function 不能始終如一地工作:
char **splitString(char *string) {
char *token = strtok(string, ","), **finalValue = NULL, **temp = NULL;
size_t wordIndex = 0;
while (token != NULL) {
temp = realloc(finalValue, sizeof(char *));
if (!temp) {
freeArray(finalValue);
finalValue = NULL;
break;
}
temp[wordIndex] = malloc((strlen(token)+1)*sizeof(char));
if (temp[wordIndex] == NULL) {
freeArray(finalValue);
finalValue = NULL;
break;
}
strcpy(temp[wordIndex], token);
printf("%s\n", temp[wordIndex]);
finalValue = temp;
printf("%s\n", finalValue[wordIndex]);
wordIndex++;
token = strtok(NULL, ",");
}
return finalValue;
It receives a string separated by commas and its supposed to split them into different strings, all of which were created via `malloc`/`realloc`.
問題出在這里: temp = realloc(finalValue, sizeof(char *));
為單個指針重新分配。 你應該寫:
temp = realloc(finalValue, (wordIndex + 2) * sizeof(char *));
您還應該在finalValue
數組的末尾設置一個NULL
指針,以標記該數組的末尾,因為 function 不會以任何其他方式返回條目數。
另請注意,當realloc()
或malloc()
失敗時,分配的字符串不會被釋放。
最后,您不應該使用strtok()
,因為它會修改源字符串。 建議使用strspn()
、 strcspn()
和strndup()
的替代方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.