Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you add chars to an array dynamically? Without the array being predefined?

Tags:

arrays

c

char

If I want to add chars to char array, I must do it like this:

#include <stdio.h>

int main() {
    int i;
    char characters[7] = "0000000";
    for (i = 0; i < 7; i++) {
        characters[i] = (char)('a' + i);
        if (i > 2) {
            break;
        }
    }

    for (i = 0; i < 7; i++) {
        printf("%c\n", characters[i]);
    }
    return 0;
}

To prevent from printing any weird characters, I must initialize the array, but it isn't flexible. How can I add characters to a char array dynamically? Just like you would in Python:

characters = []
characters.append(1)
...
like image 606
Vayn Avatar asked Mar 03 '26 03:03

Vayn


2 Answers

There is no non-ugly solution for pure C.

#include <stdio.h>

int main() {
    int i;
    size_t space = 1;                  // initial room for string
    char* characters = malloc(space);  // allocate
    for (i = 0; i < 7; i++) {
        characters[i] = (char)('a' + i);
        space++;                       // increment needed space by 1
        characters = realloc(characters, space); // allocate new space
        if (i > 2) {
            break;
        }
    }

    for (i = 0; i < 7; i++) {
        printf("%c\n", characters[i]);
    }
    return 0;
}

In practice you want to avoid the use of realloc and of course allocate the memory in bigger chunks than just one byte, maybe even at an exponetial rate. But in essence thats what happening under the hood of std::string and the like: You need a counter, which counts the current size, a variable of the current maximum size (Here it is always current size+1, for simplicity) and some reallocation if the need for space surpasses the maximum current size.

like image 68
Gunther Piez Avatar answered Mar 04 '26 15:03

Gunther Piez


Yes, of course you can add characters dynamically:

quote char[100] = "The course of true love";
      strcat( quote, " never did run smooth.";

but only if there is enough room in quote[ ] to hold the appended characters. Or maybe you are asking why, in C, you have to pre-arrange enough character storage whereas, in Python, storage is allocated dynamically. That's how the language was designed in 197x.

C99 does allow dynamically-allocated storage: storage allocated by the system at run time. And a very bad mistake it is, imo.

like image 37
Pete Wilson Avatar answered Mar 04 '26 15:03

Pete Wilson