使用使用者定義的大小分配和零初始化陣列
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int * pdata;
size_t n;
printf ("Enter the size of the array: ");
fflush(stdout); /* Make sure the prompt gets printed to buffered stdout. */
if (1 != scanf("%zu", &n)) /* If zu is not supported (Windows?) use lu. */
{
fprintf("scanf() did not read a in proper value.\n");
exit(EXIT_FAILURE);
}
pdata = calloc(n, sizeof *pdata);
if (NULL == pdata)
{
perror("calloc() failed"); /* Print error. */
exit(EXIT_FAILURE);
}
free(pdata); /* Clean up. */
return EXIT_SUCCESS;
}
該程式嘗試從標準輸入中掃描無符號整數值,通過呼叫 calloc()
函式為 int
型別的 n
個元素陣列分配一塊記憶體。記憶體被後者初始化為全零。
如果成功,則通過呼叫 free()
釋放記憶體。