Array Initialization in C, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 7.2 Free with a free account

Array Initialization in C

Programming in C · Chapter 7: Arrays, Strings, Input Validation, and Formatted OutputSection 7.2 · lesson 41 of 786 min · free with a free account

← One-Dimensional Arrays in CNext lesson: Passing Arrays to Functions in C →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Initializer lists, zero-fill rules, and designated initializers for C arrays.

  • Initialize an array with a brace initializer list in its declaration
  • Predict which elements become zero in a partial or brace-zero initialization
  • Use designated initializers to set chosen elements by index
  • Explain why a local array with no initializer holds unpredictable values

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (808 words). Read along, or search it.

Opening Question

What Is Inside a Brand-New Array

When Starlight Arcade opens in the morning, every score board must start clean. But what's inside a brand-new array? Priya once left out a board's starting values. On her laptop, it showed zeros. On Sam's test machine, strange numbers. Which machine was right? By the end, you'll know, and you'll know the neat ways to fill an array the moment it's born.

Initializer List

Curly Braces Fill Boxes in Order

To initialize a variable means to give it a value the moment it's created. For an array, put the values in curly braces. That's an initializer list. The first value goes to box zero, the second to box one, and so on. Run it. Five, ten, fifteen and twenty, in order. The braces only work in the declaration itself. Try them on a later line, and clang stops: expected expression. After the declaration, you set the boxes one at a time, or with a loop.

Partial Lists

Unlisted Boxes Become Zero

What if the list is shorter than the array? C has a friendly rule: every box you didn't list is filled with zero. Here, six boxes get only two values, seven and three. Run it. Boxes two to five all hold zero. That's guaranteed whenever an array starts with braces, even with a single value.

Brace Zero Shortcut

Zero an Array or Let C Count

That gives a one-line way to zero a whole array. Brace zero puts zero in box zero, and the rule fills the other four. The rule also lets you leave the size out. With empty brackets, C counts the values, so the list decides the size. Run it. Both arrays have five boxes, and every count is zero. But empty brackets need a list. Take the list away, and clang refuses: the array needs an explicit size, or an initializer.

Quick Check

Brace Five Fills Only Box Zero

Quick check. Brace zero gave every box a zero. So what about brace five? Here, four boxes start with just a five. What does the loop print? Pause and predict. A five, then three zeros. The single five goes into box zero, and the rest-become-zero rule fills the others. Brace zero only looks like fill-with-zero. Its zero lands in box zero, and the rule does the rest. Nothing repeats a value for you.

Common Mistake

Excess Elements Are Thrown Away

Now the opposite mistake: more values than boxes. Here, two boxes get three values. Clang warns: excess elements in array initializer. The program still builds, and the extra thirty is simply thrown away. Run it, and box one holds twenty. A warning means: this looks like a mistake. Fix the list or the size, instead of ignoring it.

Designated Initializers

Naming Boxes by Their Index

Sometimes only a few boxes need a value, and the rest should be zero. Name the box by its index in square brackets, then equals, and the value. These are designated initializers. They were added in C99, so they work with our C17 setup. Box three gets seven, box five gets two, and every box you don't name becomes zero. Run it, and that's exactly what prints. Every unnamed box is zero, and the two you named hold their values.

Quick Check

Mixing Plain and Designated Values

Quick check. This list mixes both styles: a plain two first, then box four named, with a nine. What do the six boxes hold? Pause and predict. Two, three zeros, nine, and a zero. The plain two goes into box zero, because a list always starts at the first box. The nine goes into box four, which is the fifth box. Every box that got no value becomes zero. Putting the nine in box three would forget that counting starts at zero.

Uninitialized Arrays

Local Arrays Hold Leftover Bits

The rest-become-zero rule only applies with braces. A local array declared with no starting values, like this one inside main, is different. C doesn't clean its boxes. They hold whatever bits were left in that memory, so their values are unpredictable. Clang builds it without a word, even with dash W all and dash W extra. So we don't run it. Whatever it printed would be meaningless: zeros today, strange numbers tomorrow, and something else on your friend's computer.

The Fix

Filling Every Box With a Loop

The fix is easy: use braces, or fill every box with a loop before you read it. A loop suits values from a formula, or from the player. Here, box i gets one more than i, times twenty-five. Run it: twenty-five, fifty, seventy-five, and on up to one hundred fifty.

Story Resolved

Brace Zero Cleans Every Board

Back to Priya's score board. Neither machine was right or wrong. Her boxes were never filled, so any value was just leftover bits. Zeros were luck, Sam said. Priya added brace zero, and now every board starts clean on every machine.

Key Takeaways

Ways to Start an Array Safely

To recap. An initializer list in braces fills boxes from box zero, but only in the declaration. Boxes you leave out become zero, so brace zero clears a whole array, and empty brackets let the list set the size. Designated initializers name a box by its index. And a local array with no braces holds leftovers, so fill it before you read it.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Array Initialization in C

How do you initialize an array in C when you declare it?
Put the values in curly braces in the declaration, as in int scores[4] = {5, 10, 15, 20};. The first value goes into index 0, the second into index 1, and so on. This brace syntax works only in the declaration itself. A later line such as scores = {1, 2, 3, 4}; does not compile, so after the declaration you assign elements one at a time or with a loop.
Does int a[5] = {0}; set every element of a C array to zero?
Yes, but not because the 0 is repeated. The 0 goes into a[0], and C's rule for brace initializers sets every element you did not list to zero. That is why int b[4] = {5}; holds 5, 0, 0, 0 rather than four fives. An initializer list never copies a value into other elements for you; the zero-fill rule does the rest.
What are designated initializers in C?
Designated initializers set chosen elements by index, using [index] = value inside the braces. For example, int a[6] = {[3] = 7, [5] = 2}; puts 7 in a[3] and 2 in a[5], and every element you do not name becomes zero. They were added in C99. You can mix styles: {2, [4] = 9} gives 2, 0, 0, 0, 9, 0, because plain values start at index 0.
Why does an uninitialized local array in C print random numbers?
A local array declared with no initializer, like int board[5]; inside main, is not cleared, so its elements hold whatever bits were left in that memory. The values are unpredictable: zeros on one run or machine, strange numbers on another. Compilers may not warn about it. The fix is to start the array with braces, such as {0}, or to fill every element with a loop before reading it.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →