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

  1. I created a char pointer called ‘text’ to eventually store the string.
  2. I then use malloc planning to store 200 characters
  3. 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 :

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];

Leave a Reply