How do you make a string of unknown length in c? I don't wanna make the char varName[500000] but I also don't want stuff cut off.
Use dynamic memory allocation. For instance reading a single line of arbitrary length from standard input:
Code:
(Handling of memory allocation errors omitted for brevity.)
Code:
#include <stdio.h>
#include <stdlib.h>
char *readLine(FILE *fp) {
size_t capacity = 32;
char *out = malloc(capacity);
size_t len = 0;
do {
if (len >= capacity) {
capacity *= 2;
out = realloc(out, capacity);
}
int c = fgetc(fp);
if (feof(fp)) {
len += 1; // Match end-of-loop increment to avoid dropping a char
break;
}
out[len] = (char)c;
} while (out[len++] != '\n');
len -= 1; // Fix extra increment
out[len] = 0;
return realloc(out, len);
}
int main(int argc, char **argv) {
char *s = readLine(stdin);
puts(s);
}
Thank you for the information! I would like to know how you pass this into a scanf? That is what I am trying to do.
Use sscanf after reading the input (at which time you know how big you need to make the buffer), or if GNU extensions are okay use the %ms specifier (assuming you want an arbitrary-length string as a result).
tr1p1ea wrote:
You could do a similar thing but wrap getc instead if reading from stdio I guess?
getc is equivalent to fgetc(stdin), so that's not very helpful. The trick is in the scanf family taking pointers to buffers to copy values to, which must be preallocated. %ms allocates a buffer for you, but it's not standard. Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.
» Go to Registration page
» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
Advertisement