用C初始化一个数组
时间:2020-02-23 14:32:04 来源:igfitidea点击:
在本文中,我们将了解如何在C中初始化数组。
我们可以通过多种方式来完成此操作,因此我们将它们一一列出。
让我们开始吧!
方法1:使用初始化列表初始化数组
初始化列表按列表的顺序初始化数组的元素。
例如,考虑以下代码片段:
int arr[5] = {1, 2, 3, 4, 5};
这将初始化一个大小为5的数组,其中元素{1、2、3、4、5}顺序排列。
这意味着arr [0] = 1,arr [1] = 2,依此类推。
我们不需要初始化所有元素0到4。
甚至可以只对索引0到2进行初始化。
以下代码也是有效的:
int arr[5] = {1, 2, 3};
但是现在,arr [4]和arr [5]仍将保留为垃圾值,因此您需要小心!
如果您要使用包含所有元素的初始化列表,则无需提及数组的大小。
//Valid. Size of the array is taken as the number of elements
//in the initializer list (5)
int arr[] = {1, 2, 3, 4, 5};
//Also valid. But here, size of a is 3
int a[] = {1, 2, 3};
如果要将所有元素初始化为0,则有一个快捷方式(仅适用于0)。
我们可以简单地将索引称为0。
#include <stdio.h>
int main() {
//You must mention the size of the array, if you want more than one
//element initialized to 0
//Here, all 5 elements are set to 0!
int arr[5] = {0};
for (int i=0; i<5; i++) {
printf("%d\n", arr[i]);
}
return 0;
}
输出
0 0 0 0 0
如果您使用的是多维数组,则由于数组是以行方式存储的,因此仍然可以在一个块中将它们全部初始化。
#include <stdio.h>
int main() {
int arr[3][3] = {1,2,3,4,5,6,7,8,9};
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
printf("%d\n", arr[i][j]);
return 0;
}
输出
1 2 3 4 5 6 7 8 9
类似的方法也可以用于其他数据类型,例如float,char,char *等。
#include <stdio.h>
int main() {
//Array of char* elements (C "strings")
char* arr[9] = { "Hello", [1 ... 7] = "theitroad", "Hi" };
for (int i=0; i<9; i++)
printf("%s\n", arr[i]);
return 0;
}
输出
Hello theitroad theitroad theitroad theitroad theitroad theitroad theitroad Hi
请记住,此[1…7] =" theitroad"的方法可能不适用于所有编译器。
我在Linux上开发GCC。
方法2:使用for循环在C中初始化数组
我们还可以使用" for"循环来设置数组的元素。
#include <stdio.h>
int main() {
//Declare the array
int arr[5];
for (int i=0; i<5; i++)
arr[i] = i;
for (int i=0; i<5; i++)
printf("%d\n", arr[i]);
return 0;
}
输出
0 1 2 3 4
方法3:使用指定的初始化程序(仅对于gcc编译器)
如果您将gcc用作C编译器,则可以使用指定的初始化程序将数组的特定范围设置为相同的值。
//Valid only for gcc based compilers
//Use a designated initializer on the range
int arr[9] = { [0 ... 8] = 10 };
请注意,数字之间有一个空格,并且有三个点。
否则,编译器可能会认为这是一个小数点并抛出错误。
#include <stdio.h>
int main() {
int arr[9] = { [0 ... 8] = 10 };
for (int i=0; i<9; i++)
printf("%d\n", arr[i]);
return 0;
}
输出(仅适用于gcc)
10 10 10 10 10 10 10 10 10
我们也可以将其与旧的初始化列表元素结合起来!
例如,我仅将数组索引arr [0],arr [8]设置为0,而其他数组则被初始化为10!
#include <stdio.h>
int main() {
int arr[9] = { 0, [1 ... 7] = 10, 0 };
for (int i=0; i<9; i++)
printf("%d\n", arr[i]);
return 0;
}
输出
0 10 10 10 10 10 10 10 0

