C 中的指定初始化器
在 C90 標準中,我們按照固定的順序初始化陣列,例如初始化位置 0、1、2 等索引。從 C99 標準開始,在 C 中引入了指定初始化特性。在這裡,我們可以按任意順序初始化元素。初始化可以使用陣列索引或結構成員來完成。GNUC++ 中未實現此擴充套件。
如果我們指定某些索引並放入一些值,那麼它將看起來像這樣 -
int arr[6] = {[3] = 20, [5] = 40}; or
int arr[6] = {[3]20, [5]40};這相當於以下內容
int arr[6] = {0, 0, 0, 20, 0, 40};我們還可以使用此語法設定一些元素範圍:[first … last] = value。
int arr[6] = {[2 … 4] = 10};這相當於以下內容
int arr[6] = {0, 0, 10, 10, 10, 0};如果陣列的大小未定義,那麼它可以從最大索引位置獲取大小。讓我們看看程式碼以獲得更好的概念。
示例程式碼
#include <stdio.h>
int main() {
int Array[] = {10, 20, 30, [3 ... 9] = 100, [10] = 65, 15, [80] = 50, [42] = 400 };
int i;
for (i = 0; i < 20; i++)
printf("%d ", Array[i]);
printf("
Array[%d] = %d
",80, Array[80]);
printf("Array[%d] = %d
",42, Array[42]);
printf("Size of this array: %ld
", sizeof(Array) / sizeof(Array[0]));
}輸出
10 20 30 100 100 100 100 100 100 100 65 15 0 0 0 0 0 0 0 0 Array[80] = 50 Array[42] = 400 Size of this array: 81
此指定初始化也可以對結構或聯合型別物件執行。對於它們,我們可以按任意順序使用成員變數的名稱並前面帶一個點 (.) 來初始化變數。要獲得清晰的概念,請檢視下面的程式碼。
示例程式碼
#include <stdio.h>
struct myStruct {
int x;
float y;
char z;
};
int main() {
struct myStruct str1 = {.y = 2.324, .z = 'f', .x = 78};
struct myStruct str2 = {.z = 'r'};
printf ("x = %d, y = %f, z = %c
", str1.x, str1.y, str1.z);
printf ("z = %c
", str2.z);
}輸出
x = 78, y = 2.324000, z = f z = r
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP