One-Dimensional Arrays in C, Explained with Code Examples

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

One-Dimensional Arrays in C

Programming in C · Chapter 7: Arrays, Strings, Input Validation, and Formatted OutputSection 7.1 · lesson 40 of 788 min · free with a free account

← Workshop: Multi-Function Programs and RecursionNext lesson: Array Initialization 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

Storing many values of one type under a single name in C.

  • Declare a fixed-size array and access elements by zero-based index
  • Use a for loop with less than to visit every element
  • Compute an array's element count with sizeof
  • Explain out-of-bounds access and detect it with AddressSanitizer

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 (1,100 words). Read along, or search it.

Opening Problem

Five Scores, Fifty or Five Hundred

Starlight Arcade wants to keep the five best scores of the day. Five variables, score one to score five, would do it. But what about fifty scores, or five hundred? That's five hundred names, and five hundred lines to print them. C has a better way: one name that stands for a whole row of boxes. That row is called an array.

Analogy

A Row of Numbered Lockers

Think of a row of school lockers. They all look alike and hold the same kind of thing, but each one has its own number. An array is just that: boxes of one type, side by side in memory, under one name. Each box is called an element. Its locker number is its index. Here are five int boxes called scores, and their indexes run from zero to four.

Declaration

Fixed Size, Zero-Based Indexes

To declare an array, write the type, the name, and the number of boxes in square brackets. This line means: five int boxes, called scores. The size is settled when the program is built, and it can't change later. So this is called a fixed-size array. Now the part that surprises everyone. C numbers the boxes from zero. The index is how many boxes you skip from the start. Box zero skips none, so it's the first. Box four skips four, so it's the last. Five boxes have indexes zero to four.

Element Access

Storing and Reading One Box

Each box works exactly like an int variable. Write the name and the index in square brackets, then store a number with equals. Box zero gets 120. The others follow, and box four gets 175. Careful: there's no box called scores five. The five in the declaration is a count. Later, the number in brackets is a position. Read a box back the same way, inside printf. Build and run: box zero holds 120, and box four holds 175.

Loops and Arrays

Visiting Every Box With for

Loops and arrays are best friends. A for loop that counts i from zero, up to one less than the size, visits every box in order. Inside the loop, scores of i means the box that i points at right now. On the third pass, i is two, so it's the third box. The first loop writes a typed number into each box. One box is a plain int, so scanf needs the ampersand, as in lesson 3.5. The second loop reads every box back, and adds it to the total. Sam typed five scores to test it. Every box holds his number, and the total is 660. Use one loop shape for arrays: i starts at zero, and runs while i is less than the size. Less than, never less than or equal.

Quick Check

Which Boxes Hold Twenty and Forty

Quick check. A new array, laps, has four boxes. The loop stores ten times one more than i in box i. Then it prints laps one and laps three. What two numbers appear? Pause and predict. Twenty, then forty. Box one is the second box, where i was one, and ten times two is twenty. Box three is the fourth and last box: ten times four is forty. Ten and thirty would mean counting from one, and C counts from zero.

Counting Elements

Using sizeof to Get the Length

Typing the number five all over a program is risky. Change the size, forget one place, and you have a bug. By the way, the braces here fill the boxes as the array is created. Lesson 7.2 covers them properly. The sizeof operator gives how many bytes something takes. Sizeof scores is all the boxes together. Sizeof scores zero is just one box. Divide, and you get the count. Sizeof gives a size t, a whole number that's never negative, and percent z u prints it. Run it. Twenty bytes, divided by four bytes a box, is five boxes. And the loop now follows the array, whatever its size. One warning: this trick only works where the array was declared. Inside a function it breaks, as lesson 7.3 will show.

Out of Bounds

Reading Past the Last Box

An index is in bounds from zero to the size minus one. So what happens if you ask for scores five, in a five-box array? C doesn't check. It simply goes to where a sixth box would be, whether or not that memory belongs to you. That's undefined behavior: the C rules promise nothing. An old leftover number, a changed variable, a crash, or a program that seems fine today. So we don't run it. Clang does spot this constant index, and warns: array index five is past the end of the array. Take that warning seriously. The program still builds, and any number it printed would be meaningless.

AddressSanitizer

Catching an Off-by-One Read

Don't count on that warning. The usual cause is an off-by-one loop. Less than or equal lets i reach five, so the last pass reads scores five. Build it with the same flags. Not a word from clang: a loop index is much harder for the compiler to judge. To catch it, build a checking version. Dash f sanitize equals address adds a check to every memory access, and dash g keeps line numbers. Run it, and AddressSanitizer stops the program at the bad read: a stack buffer overflow, a read of four bytes, at line seven. The access is just past the five boxes of scores. Change less than or equal to plain less than, and rebuild. Now there's no report, and the total is 660.

Quick Check

A Loop That Starts at One

Quick check. Priya's game gives each of six players three lives. Her loop counts i from one up to six. Is the loop right? Pause, and decide. It misses box zero, and writes a seventh box. The first pass starts at box one, so box zero never gets its three lives. And the last pass writes lives six, past the end. The checking build catches it: a write of four bytes, at line six. The fix: start i at zero, and keep going while i is less than six.

Wrap-Up

Testing the First, Last and One Past

Back at the arcade, Sam tested Priya's score table with exactly five scores, and everything looked right. Then he asked: what if the loop asks for a sixth? Priya went back, and made the loop stop at i less than five. The best testers poke at the edges: the first box, the last box, and one past the end.

Key Takeaways

One-Dimensional Arrays in Review

To recap. An array is a row of boxes of one type, under one name, with a size fixed when the program is built. Indexes run from zero to the size minus one, and a for loop with less than visits every box. Sizeof the whole array, divided by sizeof one box, gives the count. And C never checks an index, so stepping off the end is undefined behavior.

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 One-Dimensional Arrays in C

Why do C array indexes start at zero?
In C, an index counts how many elements to skip from the start of the array. Element 0 skips none, so it is the first, and the last element of an array of size n has index n - 1. In int scores[5], the valid indexes are 0 through 4, and there is no scores[5], because the 5 in the declaration is a count, not a position.
How do you find the number of elements in a C array?
Divide the size of the whole array by the size of one element: sizeof scores / sizeof scores[0]. With five ints of 4 bytes each, a common int size, that is 20 / 4 = 5. sizeof gives a size_t, which printf shows with %zu. The trick works only where the array itself is declared; inside a function that receives the array, it breaks.
What happens if you access an array out of bounds in C?
C does not check indexes, so reading or writing past the end is undefined behavior: the program might print a leftover value, change another variable, crash, or appear to work. Clang warns when a constant index like scores[5] is past the end of a five-element array, but it usually cannot judge a loop index. Treat any such access as a bug.
How can AddressSanitizer find an array off-by-one bug?
Build with -fsanitize=address and -g, then run the program. AddressSanitizer checks memory accesses and stops at the first bad one, reporting, for example, a stack buffer overflow with the number of bytes read and the source line. A loop using i <= 5 on a five-element array is caught on its last pass, and changing it to i < 5 removes the report.

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 →