[英]Assigning values from a static char array to a dynamically allocated char array
[英]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);
將靜態分配的數組復制到動態分配的數組后,我們可以對它做些什么,還是讓它在 memory 中腐爛? 如果是這種情況,您是否應該通過使用 malloc 創建數組的麻煩來解決 go 問題?
這只是一個假設性的問題,但是考慮到 memory 優化的最佳解決方案是什么?
以下是讓您的生活更輕松的方法:
/* 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
限定符表示:
- 可選的“m”字符。 這與字符串轉換(
%s
、%c
、%[
)一起使用,並減輕調用者分配相應緩沖區來保存輸入的需要:相反, scanf() 分配足夠大小的緩沖區,並分配地址這個緩沖區到相應的指針參數,它應該是一個指向char *
變量的指針(這個變量不需要在調用之前初始化)。 當不再需要此緩沖區時,調用者應隨后釋放(3)該緩沖區。
它是標准 C 庫的 Posix 擴展,因此任何希望與 Posix 兼容的實現都需要它,例如 Linux、FreeBSD 或 MacOS(但不幸的是,不是 Windows)。 因此,只要您使用這些平台之一,就很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.