k.s aravind k.s aravind - 2 months ago 28
C Question

C - Dynamic Memory Allocation


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


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

Enter the First String :
The First String :

mch mch

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.