How can an array of characters be entered without using a fixed length array in C? I was given an assignment to center strings in C, and was told not to use a fixed size array.
The only way to create an array without a fixed size is by using malloc, which accepts the size (in bytes) of memory you want to allocate. You will then use it as a char*, which can also accomodate array syntax. Do not forget to test that the return value is nonzero (which is the way malloc indicates that you are out of memory).
After you are done using the memory, you are then responsible for releasing it back to the system with free.
For example:
size_t size = 42; // you can read this from user input or any other source
char* str = malloc(size);
if (str == 0) {
printf( "Insufficient memory available\n" );
}
else {
// Use the memory and then...
free(str);
}
Look up the functionality of malloc and realloc.
I assume non-fixed size means dynamically allocated array - which can be obtained using malloc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With