用 C 语言初始化数组

在本文中,我们将看看如何在C中初始化一个数组。

有不同的方式,通过我们可以做到这一点,所以我们将列出他们一个接一个。


方法 1:使用初始化列表初始化数组

初始化列表以列表的顺序初始化数组的元素。

例如,考虑下面的片段:

1int arr[5] = {1, 2, 3, 4, 5};

这会初始化一个大小 5 的数组,以元素 **{1, 2, 3, 4, 5}**为顺序。

这意味着‘arr[0] = 1’,‘arr[1] = 2’,等等。

我们不需要从0到4的所有元素进行初始化,我们甚至只能从0到2的索引做。

以下代码也是有效的:

1int arr[5] = {1, 2, 3};

但是现在,arr4arr5仍然是垃圾值,所以你需要小心!

如果您正在使用包含所有元素的初始化列表,则不需要提及数组的大小。

1// Valid. Size of the array is taken as the number of elements
2// in the initializer list (5)
3int arr[] = {1, 2, 3, 4, 5};
4
5// Also valid. But here, size of a is 3
6int a[] = {1, 2, 3};

如果您想将所有元素初始化为0,则为此有一个捷径(仅为0)。

 1#include <stdio.h>
 2
 3int main() {
 4    // You must mention the size of the array, if you want more than one
 5    // element initialized to 0
 6    // Here, all 5 elements are set to 0!
 7    int arr[5] = {0};
 8    for (int i=0; i<5; i++) {
 9        printf("%d\n", arr[i]);
10    }
11    return 0;
12}

出发点( )

10
20
30
40
50

如果您正在使用多维数组,您仍然可以将它们全部初始化为一个块,因为数组以行方式存储。

1#include <stdio.h>
2
3int main() {
4    int arr[3][3] = {1,2,3,4,5,6,7,8,9};
5    for (int i=0; i<3; i++)
6        for (int j=0; j<3; j++)
7            printf("%d\n", arr[i][j]);
8    return 0;
9}

出发点( )

11
22
33
44
55
66
77
88
99

类似的方法也可用于其他数据类型,如‘float’、‘char’、‘char*’等。

1#include <stdio.h>
2
3int main() {
4    // Array of char* elements (C "strings")
5    char* arr[9] = { "Hello", [1 ... 7] = "JournalDev", "Hi" };
6    for (int i=0; i<9; i++)
7        printf("%s\n", arr[i]);
8    return 0;
9}

出发点( )

1Hello
2JournalDev
3JournalDev
4JournalDev
5JournalDev
6JournalDev
7JournalDev
8JournalDev
9Hi

请记住,这个方法与 [1... 7] = "Journaldev" 可能不会与所有编译器一起工作. 我在 Linux 上使用 GCC。

方法 2: 使用 a for loop 初始化 C 中的数组

我们还可以使用for循环来设置数组的元素。

 1#include <stdio.h>
 2
 3int main() {
 4    // Declare the array
 5    int arr[5];
 6    for (int i=0; i<5; i++)
 7        arr[i] = i;
 8
 9    for (int i=0; i<5; i++)
10        printf("%d\n", arr[i]);
11
12    return 0;
13}

出发点( )

10
21
32
43
54

方法 3:使用指定初始化器(仅适用于 gcc 编译器)

如果您使用gcc作为您的 C 编译器,您可以使用指定的初始化器,将数组的特定范围设置为相同的值。

1// Valid only for gcc based compilers
2// Use a designated initializer on the range
3int arr[9] = { [0 ... 8] = 10 };

请注意,数字之间有空间,有三个点,否则,编译器可能会认为这是一个十进制点,并扔错误。

1#include <stdio.h>
2
3int main() {
4    int arr[9] = { [0 ... 8] = 10 };
5    for (int i=0; i<9; i++)
6        printf("%d\n", arr[i]);
7    return 0;
8}

输出(仅适用于gcc)

110
210
310
410
510
610
710
810
910

我们也可以将其与我们的旧初始化器列表元素相结合!

例如,我只将数组索引 arr[0], arr[8] 设置为 0,而其他数组被指定为初始化为 10!

1#include <stdio.h>
2
3int main() {
4    int arr[9] = { 0, [1 ... 7] = 10, 0 };
5    for (int i=0; i<9; i++)
6        printf("%d\n", arr[i]);
7    return 0;
8}

出发点( )

10
210
310
410
510
610
710
810
90

结论

在本文中,我们了解了如何初始化C数组,使用不同的方法。

对于类似的文章,请参阅我们关于 C 编程的教程部分( / 社区 / 教程 / c 编程)!


Published At
Categories with 技术
Tagged with
comments powered by Disqus