简体   繁体   English

strcpy一个static的char数组到一个动态分配的char数组中保存memory

[英]Strcpy a static char array into a dynamically allocated char array to save memory

Say, in main();说,在main(); you read a string from a file, and scan it into a statically declared char array.您从文件中读取一个字符串,并将其扫描到静态声明的 char 数组中。 You then create a dynamically allocated char array with with length strlen(string).然后创建一个动态分配的 char 数组,其长度为 strlen(string)。

Ex:前任:

FILE *ifp;
char array_static[buffersize];
char *array;

fscanf(ifp, "%s", array_static);
array = malloc(sizeof(char) * strlen(array_static) + 1);
strcpy(array_static, array);

Is there anything we can do with the statically allocated array after copying it into the dynamically allocated array, or will it just be left to rot away in memory?将静态分配的数组复制到动态分配的数组后,我们可以对它做些什么,还是让它在 memory 中腐烂? If this is the case, should you even go through the trouble of creating an array with malloc?如果是这种情况,您是否应该通过使用 malloc 创建数组的麻烦来解决 go 问题?

This is just a hypothetical question, but what is the best solution here with memory optimization in mind?这只是一个假设性的问题,但是考虑到 memory 优化的最佳解决方案是什么?

Here's how to make your life easier:以下是让您的生活更轻松的方法:

/* Returns a word (delimited with whitespace) into a dynamically
 * allocated string, which is returned. Caller is responsible
 * for freeing the returned string when it is no longer needed.
 * On EOF or a read error, returns NULL.
 */
char* read_a_word(FILE* ifp) {
  char* word;
    /* Note the m. It's explained below. */
  if (fscanf(ifp, "%ms", &word) != 1)
    return NULL;
  return word;
}

The m qualifier in the scanf format means: scanf 格式中的m限定符表示:

  • An optional 'm' character.可选的“m”字符。 This is used with string conversions ( %s , %c , %[ ), and relieves the caller of the need to allocate a corresponding buffer to hold the input: instead, scanf() allocates a buffer of sufficient size, and assigns the address of this buffer to the corresponding pointer argument, which should be a pointer to a char * variable (this variable does not need to be initialized before the call).这与字符串转换( %s%c%[ )一起使用,并减轻调用者分配相应缓冲区来保存输入的需要:相反, scanf() 分配足够大小的缓冲区,并分配地址这个缓冲区到相应的指针参数,它应该是一个指向char *变量的指针(这个变量不需要在调用之前初始化)。 The caller should subsequently free(3) this buffer when it is no longer required.当不再需要此缓冲区时,调用者应随后释放(3)该缓冲区。

It's a Posix extension to the standard C library and is therefore required by any implementation which hopes to be Posix compatible, such as Linux, FreeBSD, or MacOS (but, unfortunately, not Windows).它是标准 C 库的 Posix 扩展,因此任何希望与 Posix 兼容的实现都需要它,例如 Linux、FreeBSD 或 MacOS(但不幸的是,不是 Windows)。 So as long as you're using one of those platforms, it's good.因此,只要您使用这些平台之一,就很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM