k.s aravind k.s aravind - 1 month ago 17
C Question

C - Dynamic Memory Allocation

#include<stdio.h>
#include<malloc.h>

int main()
{
char *string1;
int length;

scanf("%d", &length);

string1 = (char *)malloc(sizeof(char) * length);


printf("\n Enter the First String : ");
fgets(string1, length, stdin);

printf("\n The First String : %s ",string1);

free(string1);

return 0;
}


Can someone help me on the above code ? I trying to get the length of a string and the string as inputs. But, I am able to enter only Length of the string. After that it skips the string input part.

This is the output I am getting :

sh-4.3$ main
10

Enter the First String :
The First String :
sh-4.3$

mch mch
Answer

After typing "10<enter>" the <enter> or "\n" will remain in the stdin buffer, so you have to use getchar() after the scanf to remove it.

Also you should #include <stdlib.h> instead of malloc.h.

You malloc 1 character too less, because of the 0-terminator. string1 = malloc(length + 1); will do the job, the cast is not necessary and sizeof(char) is always 1.