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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Array Initialization in C →← Workshop: Multi-Function Programs and RecursionNext lesson: Array Initialization in C →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
How do you find the number of elements in a C array?
What happens if you access an array out of bounds in C?
How can AddressSanitizer find an array off-by-one bug?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →