[英]Array of characters in C without fixed size
如何在不使用C中的固定長度數組的情況下輸入字符數組? 我被賦予C中心字符串的賦值,並被告知不要使用固定大小的數組。
創建沒有固定大小的數組的唯一方法是使用malloc
,它接受要分配的內存大小(以字節為單位)。 然后,您將使用它作為char*
,它也可以容納數組語法。 不要忘記測試返回值是非零(這是malloc
指示您內存不足的方式)。
使用完內存后,您將負責將其free
釋放回系統。
例如:
size_t size = 42; // you can read this from user input or any other source
char* str = malloc(size);
if (str == 0) {
printf( "Insufficient memory available\n" );
}
else {
// Use the memory and then...
free(str);
}
查找malloc
和realloc
的功能。
我假設非固定大小意味着動態分配的數組 - 可以使用malloc
獲得。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.