C語言 - sizeof 運算子



sizeof 運算子是一個編譯時一元運算子。它用於計算其運算元的大小,運算元可以是資料型別或變數。它返回以位元組為單位的大小。

它可以應用於任何資料型別、浮點型別或指標型別變數。

sizeof(type or var);

當 sizeof() 用於資料型別時,它只是返回分配給該資料型別的記憶體量。在不同的機器上,輸出可能不同,例如,32 位系統顯示的輸出可能與 64 位系統不同。

示例 1:在 C 語言中使用 sizeof 運算子

請看下面的例子。它突出顯示瞭如何在 C 程式中使用 sizeof 運算子:

#include <stdio.h>

int main(){

   int a = 16;

   printf("Size of variable a: %d \n",sizeof(a));
   printf("Size of int data type: %d \n",sizeof(int));
   printf("Size of char data type: %d \n",sizeof(char));
   printf("Size of float data type: %d \n",sizeof(float));
   printf("Size of double data type: %d \n",sizeof(double));    

   return 0;
}

輸出

執行此程式碼後,您將獲得以下輸出:

Size of variable a: 4
Size of int data type: 4
Size of char data type: 1
Size of float data type: 4
Size of double data type: 8

示例 2:將 sizeof 與結構體一起使用

在這個例子中,我們聲明瞭一個結構體型別並找到結構體型別變數的大小。

#include <stdio.h>

struct employee {
   char name[10];
   int age;
   double percent;
};

int main(){
   struct employee e1 = {"Raghav", 25, 78.90};
   printf("Size of employee variable: %d\n",sizeof(e1));   
   return 0;
}

輸出

執行程式碼並檢查其輸出:

Size of employee variable: 24

示例 3:將 sizeof 與陣列一起使用

在下面的程式碼中,我們聲明瞭一個包含 10 個 int 值的陣列。對陣列變數應用 sizeof 運算子返回 40。這是因為 int 的大小為 4 位元組。

#include <stdio.h>

int main(){

   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   printf("Size of arr: %d\n", sizeof(arr));
}

輸出

執行程式碼並檢查其輸出:

Size of arr: 40

示例 4:使用 sizeof 查詢陣列的長度

在 C 語言中,我們沒有返回數值陣列中元素個數的函式(我們可以使用strlen() 函式獲取字串中的字元個數)。為此,我們可以使用sizeof() 運算子。

我們首先找到陣列的大小,然後將其除以其資料型別的大小。

#include <stdio.h>

int main(){

   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int y = sizeof(arr)/sizeof(int);

   printf("No of elements in arr: %d\n", y);
}

輸出

執行此程式碼時,它將產生以下輸出:

No of elements in arr: 10

示例 5:在動態記憶體分配中使用 sizeof

sizeof 運算子用於計算要使用malloc()calloc()函式動態分配的記憶體塊。

malloc() 函式使用以下語法

type *ptr = (type *) malloc(sizeof(type)*number);

以下語句分配一個包含 10 個整數的塊,並將它的地址儲存在指標中:

int *ptr = (int *)malloc(sizeof(int)*10);

當 sizeof() 用於表示式時,它返回表示式的 size。這是一個例子。

#include <stdio.h>

int main(){

   char a = 'S';
   double b = 4.65;

   printf("Size of variable a: %d\n",sizeof(a));
   printf("Size of an expression: %d\n",sizeof(a+b));

   int s = (int)(a+b);
   printf("Size of explicitly converted expression: %d\n",sizeof(s));

   return 0;
}

輸出

執行程式碼並檢查其輸出:

Size of variable a: 1
Size of an expression: 8
Size of explicitly converted expression: 4

示例 6:C 語言中指標的大小

sizeof()運算子返回相同的值,而不管型別如何。這包括內建型別、派生型別或雙指標指標

#include <stdio.h>

int main(){

   printf("Size of int data type: %d \n", sizeof(int *));
   printf("Size of char data type: %d \n", sizeof(char *));
   printf("Size of float data type: %d \n", sizeof(float *));
   printf("Size of double data type: %d \n", sizeof(double *));
   printf("Size of double pointer type: %d \n", sizeof(int **));
}

輸出

執行程式碼並檢查其輸出:

Size of int data type: 8
Size of char data type: 8
Size of float data type: 8
Size of double data type: 8
Size of double pointer type: 8
c_operators.htm
廣告