简体   繁体   English

将长动态字符串拆分为 c 中的字符串数组

[英]splitting a long dynamic string into an array of strings in c

I'm pretty new to C and can figure out why this function doesn't work consistently whatsoever:我对 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`.

The problem is here: temp = realloc(finalValue, sizeof(char *));问题出在这里: temp = realloc(finalValue, sizeof(char *)); reallocates for a single pointer.为单个指针重新分配。 You should write:你应该写:

temp = realloc(finalValue, (wordIndex + 2) * sizeof(char *));

You should also set a NULL pointer at the end of the finalValue array to mark the end of this array as the number of entries is not returned by the function in any other way.您还应该在finalValue数组的末尾设置一个NULL指针,以标记该数组的末尾,因为 function 不会以任何其他方式返回条目数。

Also note that the allocated strings are not freed when realloc() or malloc() fails.另请注意,当realloc()malloc()失败时,分配的字符串不会被释放。

Finally, you should not use strtok() because it modifies the source string.最后,您不应该使用strtok() ,因为它会修改源字符串。 An alternative approach with strspn() , strcspn() and strndup() is recommended.建议使用strspn()strcspn()strndup()的替代方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM