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?