将静态 char 数组 strcpy 为动态分配的 char 数组以节省内存
Strcpy a static char array into a dynamically allocated char array to save memory
比如,在 main();
中,您从文件中读取了一个字符串,并将其扫描到一个静态声明的 char 数组中。然后创建一个动态分配的 char 数组,长度为 strlen(string).
例如:
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);
在将静态分配的数组复制到动态分配的数组后,我们可以对它做些什么,还是让它在内存中腐烂?如果是这种情况,您是否还要麻烦使用 malloc 创建数组?
这只是一个假设性问题,但考虑到内存优化的最佳解决方案是什么?
以下是让您的生活更轻松的方法:
/* 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;
}
scanf格式中的m
限定符表示:
- An optional 'm' character. 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). The caller should subsequently free(3) this buffer when it is no longer required.
它是对标准 C 库的 Posix 扩展,因此任何希望 Posix 兼容的实现都需要它,例如 Linux、FreeBSD 或 MacOS(但,不幸的是,不是 Windows)。因此,只要您使用这些平台之一,就很好。
比如,在 main();
中,您从文件中读取了一个字符串,并将其扫描到一个静态声明的 char 数组中。然后创建一个动态分配的 char 数组,长度为 strlen(string).
例如:
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);
在将静态分配的数组复制到动态分配的数组后,我们可以对它做些什么,还是让它在内存中腐烂?如果是这种情况,您是否还要麻烦使用 malloc 创建数组?
这只是一个假设性问题,但考虑到内存优化的最佳解决方案是什么?
以下是让您的生活更轻松的方法:
/* 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;
}
scanf格式中的m
限定符表示:
- An optional 'm' character. 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 achar *
variable (this variable does not need to be initialized before the call). The caller should subsequently free(3) this buffer when it is no longer required.
它是对标准 C 库的 Posix 扩展,因此任何希望 Posix 兼容的实现都需要它,例如 Linux、FreeBSD 或 MacOS(但,不幸的是,不是 Windows)。因此,只要您使用这些平台之一,就很好。