Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading