1

I am trying store sentences in my string variable after allocating the length of the string by using the malloc function

here is my code:

int main(void)
{
    int maxleng;
    printf("enter numbers to designate maximum length of the string: ");
    scanf("%d", &maxleng);

    char * string = (char*)malloc(sizeof(char) * maxleng);
    if (string == NULL)
    {
        puts("fails to allocate memory in string");
    }

    printf("enter any sentence to store in string \n");
    fgets(string, maxleng, stdin);


    return 0; 
}

however, the problem is that I am unable to store any words in the string after I run this code. It just allows me to designate max number, print sentence before fgets function then ends the program.

scanf("%[^\n]s", string);

I tried this code instead of fgets function but it still happens to me. Is there any solution for this?

udon2231
  • 11
  • 2
  • Don't mix `fgets(..., stdin)` and `scanf`. – Jabberwocky Oct 12 '20 at 09:27
  • What @user3121023 said, except that it isn't necessarily a newline that gets left in the input stream, it is the first non-matching character after reading the integer value (assuming `scanf` returns 1 to indicate that it successfully read one item) or nothing if end-of-file is reached. Your code ought to check the return value of `scanf`. – Ian Abbott Oct 12 '20 at 09:27
  • [One of the many, *many* duplicates of this issue.](https://stackoverflow.com/questions/59697851/scanf-before-fgets-interference). – WhozCraig Oct 12 '20 at 09:36
  • I changed scanf into fgets then it seems like it works. Thanks guys. – udon2231 Oct 12 '20 at 10:03

0 Answers0