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.
3 Answers
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);
}
9 Comments
pmg
No! Don't cast the return value from
malloc. In C, that is, at best, redundant and may hide an error the compiler would have caught without the cast.Mahesh
@pmg Could you please give an example where compiler is hiding an actual error message. I tried to produce one but failed though.
Jon
@pmg: You are of course right, that's C++ habits at work. Edited to fix, thank you.
Jon
@MattJoiner: Are you referring to VLAs? Please keep in mind the level of the person asking the question, and the spirit of the assignment. Also, I would prefer to keep the discussion civil.
pmg
@Mahesh: failure to include
<stdlib.h> leds compiler to assume malloc returns an int. See ideone.com/dQUo8 |
You can do dynamic memory allocation by malloc.
int main()
{
int i;
printf ("How long do you want the string? ");
scanf ("%d", &i);
char *buffer = malloc (i+1);
}
1 Comment
pmg
The cast is, at best, redundant and may hide an error the compiler would have caught withiut the cast.