Tutorial

Initialize an Array in C

Published on August 3, 2022
Default avatar

By Vijaykrishna Ram

Initialize an Array in C

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this article, we’ll take a look at how we will initialize an array in C.

There are different ways through which we can do this, so we’ll list them all one by one. Let’s get started!


Method 1: Initialize an array using an Initializer List

An initializer list initializes elements of an array in the order of the list.

For example, consider the below snippet:

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

This initializes an array of size 5, with the elements {1, 2, 3, 4, 5} in order.

This means that arr[0] = 1, arr[1] = 2, and so on.

We don’t need to initialize all the elements 0 to 4. We can even do only from indices 0 to 2.

The following code is also valid:

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

But now, arr[4] and arr[5] will still remain garbage values, so you need to be careful!

If you’re using an initializer list with all elements, you don’t need to mention the size of the array.

// 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};

If you want to initialize all the elements to 0, there is a shortcut for this (Only for 0). We can simply mention the index as 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;
}

Output

0
0
0
0
0

If you’re using multi-dimensional arrays, you can still initialize them all in one block, since arrays are stored in a row-wise manner.

#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;
}

Output

1
2
3
4
5
6
7
8
9

A similar method can also be used for other datatypes, like float, char, char*, etc.

#include <stdio.h>

int main() {
    // Array of char* elements (C "strings")
    char* arr[9] = { "Hello", [1 ... 7] = "JournalDev", "Hi" };
    for (int i=0; i<9; i++)
        printf("%s\n", arr[i]);
    return 0;
}

Output

Hello
JournalDev
JournalDev
JournalDev
JournalDev
JournalDev
JournalDev
JournalDev
Hi

Remember, this method with [1 … 7] = “Journaldev” might not work with all compilers. I work on GCC in Linux.

Method 2: Initialize an array in C using a for loop

We can also use the for loop to set the elements of an array.

#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;
}

Output

0
1
2
3
4

Method 3: Using Designated Initializers (For gcc compiler only)

If you’re using gcc as your C compiler, you can use designated initializers, to set a specific range of the array to the same value.

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

Note that there is a space between the numbers and there are the three dots. Otherwise, the compiler may think that it is a decimal point and throw an error.

#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;
}

Output (for gcc only)

10
10
10
10
10
10
10
10
10

We can also combine this with our old initializer list elements!

For example, I am setting only array index arr[0], arr[8] as 0, while the others are designated initialized to 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;
}

Output

0
10
10
10
10
10
10
10
0

Conclusion

In this article, we learned how we could initialize a C array, using different methods.

For similar articles, do go through our tutorial section on C programming!


Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Vijaykrishna Ram

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel