C語言中calloc() 與 malloc() 的區別


calloc()

calloc() 函式代表連續位置。它的工作原理類似於 malloc(),但它分配多個相同大小的記憶體塊。

以下是 C 語言中 calloc() 的語法:

void *calloc(size_t number, size_t size);

這裡:

number - 要分配的陣列元素個數。

size - 以位元組為單位分配的記憶體大小。

以下是在 C 語言中使用 calloc() 的示例:

示例

 線上演示

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) calloc(n, sizeof(int));
   if(p == NULL) {
      printf("
Error! memory not allocated.");       exit(0);    }    printf("
Enter elements of array : ");    for(i = 0; i < n; ++i) {       scanf("%d", p + i);       s += *(p + i);    }    printf("
Sum : %d", s);    return 0; }

輸出

Enter elements of array : 2 24 35 12
Sum : 73

在上述程式中,記憶體塊由 calloc() 分配。如果指標變數為空,則沒有記憶體分配。如果指標變數不為空,則使用者必須輸入陣列的四個元素,然後計算元素的總和。

p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
   printf("
Error! memory not allocated.");    exit(0); } printf("
Enter elements of array : "); for(i = 0; i < n; ++i) {    scanf("%d", p + i);    s += *(p + i); }

malloc()

malloc() 函式用於分配請求大小的位元組,並返回指向分配記憶體第一個位元組的指標。如果失敗,則返回空指標。

以下是 C 語言中 malloc() 的語法:

pointer_name = (cast-type*) malloc(size);

這裡:

pointer_name - 指標的任意名稱。

cast-type - 您希望 malloc() 分配的記憶體轉換為的資料型別。

size - 以位元組為單位分配的記憶體大小。

以下是在 C 語言中使用 malloc() 的示例:

示例

 線上演示

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));
   if(p == NULL) {
      printf("
Error! memory not allocated.");       exit(0);    }    printf("
Enter elements of array : ");    for(i = 0; i < n; ++i) {       scanf("%d", p + i);       s += *(p + i);    }    printf("
Sum : %d", s);    return 0; }

以下是輸出:

輸出

Enter elements of array : 32 23 21 8
Sum : 84

在上述程式中,聲明瞭四個變數,其中一個是儲存 malloc 分配的記憶體的指標變數 *p。陣列的元素由使用者列印,並列印元素的總和。

int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
   printf("
Error! memory not allocated.");    exit(0); } printf("
Enter elements of array : "); for(i = 0; i < n; ++i) {    scanf("%d", p + i);    s += *(p + i); } printf("
Sum : %d", s);

更新於: 2020-06-26

2K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.