我必须从stdin中读取一个字符串,以二进制方式分配内存而不浪费它。
我做过,但我不相信,因为这样我认为我浪费了记忆!

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

}

知道吗?我应该一次读一个字吗?

最佳答案

要声明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;
}

关于c - 读取字符串而不浪费内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18557614/

10-10 21:10