user2809184
user2809184

Reputation:

Constantly adjusting the size of an array with C

In my application, we take in char values one at a time and we need to be able to but them into a string. We are assembling these strings one by one by putting the char values into a char array, then clearing the array. However the strings are each different lengths and we are unable to determine the size of the string. How can we change the sizes of the array to add more space as we need it?

Also, how can we print out the array?

Upvotes: 0

Views: 71

Answers (2)

Tim Pierce
Tim Pierce

Reputation: 5674

If the array was dynamically allocated with malloc, you can resize it with realloc:

int array_size = 1024;
char *array = (char *) malloc(array_size);

int n = 0;
char c;
while ((c = getchar()) != EOF) {
    array[n++] = c;
    if (n >= array_size) {
        array_size += 1024;
        array = (char *) realloc(array_size);
    }
}
array[n] = '\0';

For printing out the contents of the array, you can simply pass it to printf or puts:

printf("%s\n", array);
puts(array);

Upvotes: 4

Pandrei
Pandrei

Reputation: 4951

if you don'y know the size you are going to need and are adding one character at a time you can consider using a linked list. It can grow as much as you need it to. The disadvntages would be lookup is kind of slow, and if you need to free the memory, or clear it you would have to do this for each element, one at a time.

You can also take the dynamic array approach: allocate a certain size which you consider large enough and when that is 80% full, allocate a new buffer, twice as large and copy the contents of the old one in the new, larger one.

Upvotes: 0

Related Questions