我必须从标准输入读取一个字符串,动态分配内存而不浪费它。我已经这样做了,但我不相信它,因为这样我觉得我浪费了内存!
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *alloc_memory(int n)
{
char *p;
p=malloc(n*sizeof(char));
if(p==NULL)
{
fprintf(stderr,"Error in malloc\n");
exit(EXIT_FAILURE);
}
return p;
}
int main(int argc, char *argv[])
{
if(argc != 1)
{
fprintf(stderr,"Usage: %s \n",argv[0]);
return EXIT_FAILURE;
}
char string[64];
int lung;
char *p,*s,*w;
printf("Insert string: \n");
p=fgets(string,63,stdin);
if(p==NULL)
{
fprintf(stderr,"Error in fgets\n");
exit(EXIT_FAILURE);
}
printf("You've inserted: %s", string);
lung=strlen(p);
s = alloc_memory(lung+1);
w=strncpy(s,p,lung);
printf("Final string:%s", w);
return EXIT_SUCCESS;
}
任何想法?我应该一次读一个字符吗?