'is there a way to use fgets size dynamically
So im learning about pointers and dynamic memory and how am experimenting with fgets.
So i want to take in a string input into a pointer using fgets, but i want fgets size to change dynamically with malloc function that i used for the pointer is there a way to do it ? e.g.
int main(){
char *text;
text =(char *)malloc(200 * sizeof(char));
fgets(text, n, stdin);
return 0;
}
Explanation
- I created a char pointer called 'text' to eventually store the string.
- I then use malloc planning to store 200 characters
- Next i want to use fgets to take in the string input by the user Where 'n' is the size of text that malloc allocated for the pointer?
i have tried fgets(text, sizeof(text), stdin);
but it does not work ?
Solution 1:[1]
This will not work since sizeof(ptr)
where ptr is a dynamic pointer to a char array will always be size of pointer (8 for 64bits machines), not size of array. You would have to:
- either store 200 in some kind of variable; or
- statically allocate memory for text, like
char text[200];
Solution 2:[2]
A common approach is to allocate some upper bounded size buffer and then right-size it.
char *fgets_alloc(FILE *f, size_t max_size) {
char *buf = malloc(max_size);
if (buf) {
if (fgets(buf, max_size, f)) {
size_t sz = strlen(buf) + 1;
void *ptr = realloc(buf, sz); // Reduce allocation
if (ptr) {
buf = ptr;
}
return buf;
}
free(buf);
}
return NULL;
}
To Do: code to handle excessively long lines and max_size
outside int
range.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jakub Bednarski |
Solution 2 | chux - Reinstate Monica |