c中的动态length/sized char数组

Dynamically length/sized char array in c

我正在尝试使用动态 length/size 在 c 中创建动态字符数组(向量)。

这是我的尝试:

#include <stdio.h>
#include <stdlib.h>

void push_back(char **arr, char *element, int *counter) {
    if (*counter > 0) {
        arr = realloc(arr, *counter * sizeof(char *));
    }
    arr[*counter] = element;
    (*counter)++;
}

int main() {
    char **arr = malloc(1 * sizeof(char *));
    int counter = 0;

    push_back(arr, "element", &counter);
    push_back(arr, "element2", &counter);
    push_back(arr, "element3", &counter);
    push_back(arr, "element4", &counter);
    push_back(arr, "element5", &counter);
    push_back(arr, "element6", &counter);

    for (int i=0; i<counter; i++) {
        printf("%s <-\n", (char *)arr[i]);
    }

    free(arr[i]);
    return 0;
}

我从 stdout 收到以下错误:

realloc(): invalid next size
Aborted

我做错了什么?

你需要三重指针 *** (wrrrr.....) 或者只是 return 重新分配指针。

char ** push_back(char **arr, char *element, int *counter) {
    *counter += 1;

    arr = realloc(arr, *counter * sizeof(char *));
    arr[*counter - 1] = element;
    return arr;
}

int main() {
    char **arr = NULL;
    int counter = 0;

    arr = push_back(arr, "element", &counter);
    arr = push_back(arr, "element2", &counter);
    arr = push_back(arr, "element3", &counter);
    arr = push_back(arr, "element4", &counter);
    arr = push_back(arr, "element5", &counter);
    arr = push_back(arr, "element6", &counter);

    for (int i=0; i<counter; i++) {
        printf("%s %d <-\n", arr[i], counter);
    }

    free(arr);
    return 0;
}

您不需要 malloc 然后检查计数器的值。 https://godbolt.org/z/xnaxKo

PS Yuo should always check the result of the malloc (and friends).