xxssd_coder
xxssd_coder

Reputation: 3

Dynamically length/sized char array in c

I am attempting to create a dynamic char array (vector) in c with dynamic length/size.

Here is my attempt:

#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;
}

I receive the following error from stdout:

realloc(): invalid next size
Aborted

What am I doing wrong?

Upvotes: 0

Views: 78

Answers (1)

0___________
0___________

Reputation: 67476

you need triple pointer *** (wrrrr.....) or just return realloced pointer back.

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;
}

You do not need to malloc and then check the value of the counter. https://godbolt.org/z/xnaxKo

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

Upvotes: 2

Related Questions