One-Dimensional Arrays, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 6.2 Free with a free account

One-Dimensional Arrays

C++ Programming · Chapter 6: ArraysSection 6.2 · lesson 38 of 84video coming soon

← Arrays and Vectors IntroducedNext lesson: Filling Arrays With Starting Data →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

Declaring single-row collections.

  • Declare an array, and know why its size is fixed at build time
  • Read, assign and traverse its elements
  • Explain what an out-of-range access really does
  • Compute a length with sizeof; avoid = and == on arrays

Transcript

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

Opening Question

One Name for Many Values

Five test results need five names. Five hundred need something else entirely. An array is the answer C plus plus inherited from C. It's one name covering a run of values of the same type, laid end to end in memory, and reached by number rather than by name. It's fast, it's simple, and it won't warn you when you reach past the end. So learning what it doesn't do matters as much as learning what it does.

Declaration

Declaring a Fixed-Size Array

An array is a fixed number of values of the same type, stored one after another. Declaring one states three things. The type of every element, the name of the whole collection, and how many elements there are, in square brackets. This reserves room for five whole numbers, named collectively ok. It doesn't put anything in them. What the slots contain is whatever the memory already held. Here the length is a named constant, size, set to 5. It's fixed at build time, so it's allowed. The array occupies 20 bytes.

Size Rules

Sizes Must Be Compile-Time Constants

The number in the brackets has to be a compile-time constant: a value the compiler can work out while building, not one discovered while running. A literal is allowed. A constant is allowed. So is arithmetic the compiler can do itself, like 4 times 3. An ordinary int n, holding 5, isn't standard C plus plus, even though n happens to hold 5. It could hold anything by the time the line runs. And a size of zero isn't allowed either: an array needs at least one element. Asked to enforce the standard, the compiler refuses both. Pedantic errors turns every extension into a refusal: one error for the run-time size, and one for the zero.

Rationale

Why the Compiler Needs the Size

The reason follows from what a declaration does. The compiler is reserving a specific quantity of memory, and must know the quantity to reserve it. You may see an array sized by an ordinary variable work anyway. Several compilers accept a run-time size as an extension, so it may build on your machine. It's still not standard C plus plus, and code relying on it will fail elsewhere. When a size genuinely isn't known until the program runs, arrays are the wrong tool. A growable container is what's wanted, like the vector met earlier.

Memory Layout

One Continuous Block of Slots

The five slots aren't five separate things scattered about memory. They occupy one continuous block, each element exactly as wide as its type, with no gaps. With four-byte ints, scores 0 sits at byte 0, scores 1 at byte 4, up to scores 4 at byte 16. The block is 20 bytes. Scores 5, at byte 20, isn't yours. It's past the end. An array doesn't know its own length. But because every element is the same size, the length can be calculated: the size of the whole array, divided by the size of one element. 20 bytes for the array, 4 for one element, and 20 divided by 4 is 5. Divide by the size of an actual element, rather than a literal 4, so it stays correct if the type changes. It works only where the compiler can see the array's declaration. Carry the array somewhere else, and the information is lost. That's the subject of lesson 6.4.

Element Access

Reading and Writing by Index

An individual element is named by putting its index in square brackets after the array's name. It then behaves exactly like an ordinary value of the element type. Here, scores 0 is set to 88, and the others are filled in. Scores 2 is printed, then increased by 4. Two facts carry most of the weight. The first index is zero, not one. So the last index is one less than the length: for five elements, index 4. An array of five elements has no scores 5, and writing one is the single most common array fault there is.

Traversal

Counted Loops and Range-Based For

Because indices run from 0 to one less than the length, a counted loop fits an array exactly. Start i at 0, and continue while i is less than 5. That pairing is worth learning as a single unit, because the alternatives are all off by one. When you want every element and don't care about positions, there's a form that removes the counter entirely: for int s, colon, scores. Read it as, for each s in scores. There's no index, no condition, and no update, so there's nothing to get off by one. Both forms print the same five numbers.

Common Mistake

Range Loop Variable Is a Copy

The range-based form reads. It doesn't write. The loop variable receives a copy of each element in turn, so assigning to it changes nothing in the array. A loop that sets every x to zero leaves the array holding 1, 2, 3, 4. Modifying elements through this form is possible, but needs the loop variable to refer to the element, rather than copy it. That comes once references are introduced.

Decision Guide

Choosing the Right Loop Form

Choosing a traversal is straightforward. To read every element when positions don't matter, use the range-based form. It's shorter, and structurally incapable of running past the end. To know which position you're at, use an index loop: the counter is the position. To change elements in place, use an index loop, because the range form gives you a copy. To visit only part of the array, or step by more than one, use an index loop. And to walk two arrays together, use an index loop, because one counter indexes both.

Key Warning

No Bounds Checking at Run Time

Here's the most important thing in this lesson. C plus plus doesn't check that an index is within range. Not while the program runs. An out-of-range access isn't reported, isn't refused, and isn't detected. It simply does something, and what it does isn't defined. The reason is arithmetic. For scores, index i, the machine multiplies i by the size of one element, and adds that to the address where the array begins. Scores 2 becomes the start plus 8 bytes: inside the array. Scores 7 becomes the start plus 28 bytes: somewhere else entirely. Nothing in that calculation involves the length. The array's boundary is a fact about your program, not about the memory. The machine sees no line there.

Worked Example

Writing Past the End of data

Here's what actually happens. This program writes 7777 into data, for i up to and including 5, but data has only three elements. Writes land on whatever sits beyond the array. So build it as a checking build, with the address sanitizer switched on, and run it. The checking build detects that something is wrong, and stops the program with an error report: a stack buffer overflow, just past the array data. Another build, or another compiler, might quietly change the neighboring variable and finish normally. Same category of mistake, two entirely different outcomes. And neither is the language's fault, because the language never promised anything here. This is the undefined behavior met in chapter two.

Compiler Warnings

Constant Indexes Get Warnings, Computed Ones Don't

A compiler may notice when the index is a visible constant, like this one. It warns, and still builds. But a computed index, like the loop counter in the last program, gets no compiler warning at all.

Possible Outcomes

Every Result Is Permitted, None Reliable

All of these outcomes are permitted, and none can be relied upon. It may appear to work. The program is wrong, with no sign of it, until the memory layout changes for some unrelated reason. Another variable may change. The symptom points at innocent code, and the array is never suspected. The program may stop. That's alarming, but it's by far the most useful outcome, because it fails immediately and near the cause. Or reading gives garbage that looks plausible. So bounds are your responsibility, entirely. Check every index, or produce it from a loop that can't exceed the range. That's why the range-based form is worth preferring where it fits. It can't produce an out-of-range index, because it never forms one.

Array Copying

Why b Equals a Won't Compile

Given two arrays of the same type and length, you'd expect to copy one into the other, and compare them. Start with the copy. Writing b equals a doesn't compile. The compiler reports that an array type isn't assignable. This is the good outcome: the mistake can't survive. An array name isn't a value that can be copied about. It stands for a block of storage reserved at a fixed place. To copy the contents, copy the elements, in a loop.

Array Comparison

Comparing Addresses, Not Contents

Comparison is different: it compiles. Both arrays hold 1, 2, 3. Pause and predict: what does a equals equals b print? It builds with a warning, and prints false. Used this way, an array name yields the address where its block begins. So the comparison asks whether the two arrays are stored in the same place, and two distinct arrays never are. That's worse than the failed copy: it compiles, and it's false even though every element matches. The answer is correct. The question wasn't the one intended. To compare contents, loop over the indexes comparing pairs, stopping at the first mismatch.

Key Terms

Vocabulary for Arrays and Bounds

A few key terms. An array is a fixed number of same-typed values in one continuous block of memory. A compile-time constant is a value the compiler can determine while building. It's the only thing permitted as an array size. Traversal means visiting every element in turn. The bounds are the valid indexes, zero to length minus one, and nothing enforces them. And undefined behavior is a situation on which the language imposes no requirements, so no outcome may be relied upon.

Key Takeaways

Array Rules and a Closing Puzzle

To summarize. An array's size must be a compile-time constant. Indexes run from zero to the length minus one, so loop while i is less than the length. Prefer the range-based form when you want every element. An out-of-range access is undefined, and nothing reports it. Bounds are your responsibility. The length is the size of the array over the size of one element. And copy and compare arrays with loops, not with equals. Here's something to think about. Two programs make the same out-of-range write. One crashes, and one finishes quietly with wrong values. Which is more helpful, and why is that answer counterintuitive?

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
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

C++ Programming 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

Why does a C++ array size have to be a constant?
The size must be a compile-time constant because the compiler has to know how much memory to reserve when it builds the program. A literal, a named constant, or arithmetic like 4 * 3 works. An ordinary int variable does not, and neither does a size of zero. Some compilers accept run-time sizes as an extension, but that is not standard C++. Use a vector when the size is unknown until runtime.
What happens if I access an array index that is out of range in C++?
The behavior is undefined, because C++ does not check array bounds at run time. The machine just adds the index times the element size to the array's starting address, and the array's length plays no part. The program might crash, quietly change another variable, or appear to work. Valid indexes run from 0 to length minus 1, and keeping within them is your job.
How do I find the length of an array in C++ using sizeof?
Divide the size of the whole array by the size of one element: sizeof(scores) / sizeof(scores[0]). For five 4-byte ints, that is 20 / 4, which gives 5. Using an actual element instead of a literal 4 keeps it correct if the type changes. It works only where the compiler can see the array's declaration, so it fails once the array is passed elsewhere.
Why doesn't b = a or a == b work to copy or compare two arrays in C++?
An array name stands for a fixed block of storage, not a value you can copy. Writing b = a fails to compile because array types are not assignable. Writing a == b compiles, but it compares starting addresses, so two separate arrays give false even with identical contents. To copy or compare arrays, use a loop over the indexes, checking pairs of elements.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) 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 C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 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 C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 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 C++ Programming.

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

C++ Programming
3 credits · NCCRS
Enroll →