How would you add chars to an array dynamically? Without the array being predefined?
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)
...
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.
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.
You cannot unless you use Linked Lists or some other custom data structure.
精彩评论