Reputation: 11
I'm trying to allocate memory for strings, but no matter what I do, I always allocate memory for seven characters, even changing the size. can someone help please?
#include <stdio_ext.h>
#include <stdlib.h>
int main()
{
char *s;
int n;
printf("string size? ");
scanf("%d",&n);
__fpurge(stdin);
s = (char *)malloc((n+1) * sizeof(char));
if (!s)
{
printf("not possible\n");
exit(0);
}
printf("Enter the string: ");
fgets(s, sizeof(s), stdin);
printf("String: %s\n",s);
free(s);
}
Upvotes: 1
Views: 156
Reputation: 46
sizeof(s)
returns size of pointer which is 8 in your case, you should rewrite this fgets(s, sizeof(s), stdin);
with this fgets(s, n + 1, stdin);
.
Upvotes: 2