Hi
I am trying a thing. in that i want to get lines of text which has special chars,numbers and chars and i dont want to allocate memory at the beginning. i want to allocate memory exactly needed for the input given.i dont want to waste memory.
Hi
I am trying a thing. in that i want to get lines of text which has special chars,numbers and chars and i dont want to allocate memory at the beginning. i want to allocate memory exactly needed for the input given.i dont want to waste memory.
You can do it but it wastes time by only allocating the memory needed. That's a lot of calls to realloc.i dont want to waste memory.
If you want it to be fast you have to waste memory somewhere. Something like an array that holds parts of the string so you can use fread or fgets and call realloc less often.Code:char *getline(void) { char *s = NULL; int n = 0; int ch; do { ch = getchar(); s = (char*)realloc(s, n + 2); s[n++] = ch; } while ( ch != '\n' ); s[n] = '\0'; return s; }
Use a temp buffer (typically BUFSIZ in size) to read a line.
Measure it's length, then allocate that much space, copy the line and save for later.
Repeat until done.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.