【问题标题】:Dynamically length/sized char array in cc中动态长度/大小的char数组
【发布时间】:2020-11-11 04:35:35
【问题描述】:

我正在尝试在 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;
}

我从标准输出收到以下错误:

realloc(): invalid next size
Aborted

我做错了什么?

【问题讨论】:

标签: arrays c dynamic malloc realloc


【解决方案1】:

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

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 Yu应该总是检查malloc(和朋友)的结果。

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2018-10-10
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多