0

我必须从标准输入读取一个字符串,动态分配内存而不浪费它。我已经这样做了,但我不相信它,因为这样我觉得我浪费了内存!

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

}

任何想法?我应该一次读一个字符吗?

4

1 回答 1

2

char str[64](string不是变量的好名字,它可能会导致歧义) 只是临时声明,只是将它放在本地上下文中:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * alloc_memory(size_t n)
{
  char * p = malloc(n); /* * sizeof(char) is always 1 */

  if (p == NULL)
  {
    fprintf(stderr, "Error in malloc() when trying to allocate %zu bytes.\n", n);
    exit(EXIT_FAILURE);
  }

  memset(p, 0, n); /* Avoid having strncpy() choke .. later down in this example. */

  return p;
}

int main(int argc, char * argv[])
{
  if (argc != 1)
  {
    fprintf(stderr, "Usage: %s \n", argv[0]);
    return EXIT_FAILURE;
  }

  {
    char * w = NULL;

    printf("Insert string: ");

    {
      char str[64]; /* here str is allocated */
      char * p = fgets(str, 63, stdin);
      if (p == NULL)
      {
        fprintf(stderr, "Error in fgets().\n");
        exit(EXIT_FAILURE);
      }

      printf("You've inserted: '%s'\n", str);

      {
        size_t lung = strlen(p);
        char * s = alloc_memory(lung + 1);

        w = strncpy(s, p, lung);
      }
    } /* here "str" is deallocated */

    printf("Final string: '%s'\n", w);
  }

  return EXIT_SUCCESS;
}
于 2013-09-01T10:51:31.100 回答