0

I'm starting to learn about arrays in C++, and I can't seem to understand why the array continues after the loop has been exceeded as well as the values they return.

int array[5] = {0, 1, 2, 3, 4}
int i;
i=0;
for (i=0, i < 9, i+=2)
{
    printf("%d ", array [i]);
}

Why does the array print out values of 0 or random numbers after 4?

*I understand I'm printing out the 1st, 3rd, 5th, 7th and 9th number

Brian
  • 14,610
  • 7
  • 35
  • 43
jj6847
  • 9
  • 3

4 Answers4

1

You're printing out the 1st, 3rd, 5th, 7th, and 9th numbers of an array that only has 5 numbers.

After you go beyond the 5th number, you're printing undefined values from memory that do not belong to your array.

Why does the loop continue beyond the actual length of the array? Because you told it to, and C++ will allow that.

Brian
  • 14,610
  • 7
  • 35
  • 43
0

Because the array index syntax is just a shortcut for pointer math:

array[i]

Is the same as:

*(array + i)

In your case that math happens to work out to an address in memory that exists, is addressable by your program, and contains some random data.

Accessing this data is known as a buffer overflow bug.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
0

An array in C++ is basically a syntactic wrapper around a pointer and offset. An array variable can be passed to a same typed pointer argument.

array[i]

is the same as

*(array + i)

C++ doesn't do bounds checking on arrays for you the way Java or C# does. The principle is C++ is that the language doesn't do anything you didn't ask for. Checking if you are accessing an array out of bounds and throwing an exception adds overhead, which is unnecessary if you know that you will access in bounds.

When you access out of bounds memory that is still accessible by your application what you end up getting is uninitialized memory.

You could programatically get the correct number of elements in your array, or for the same code you could use an std::vector and check the size():

#include <vector>

std::vector<int> vals = {0, 1, 2, 3, 4};
for (int i=0, i < vals.size(), i+=2)
{
    printf("%d ", array [i]);
}
Jay Miller
  • 2,184
  • 12
  • 11
-1

I am a C# developer, but it appears to me that you have an array with 5 elements and you are trying to print elements that don't exist. Try changing your initial statement to: int array[9] = {0,1,2,3,4,5,6,7,8,9} and see if that works.

JustMeToo
  • 325
  • 1
  • 14
  • What is so wrong with this answer that I get dinged? Someone already mentioned that the behavior was undefined (correct). So I just said what to do to fix it (rather than duplicate that reply.) Maybe I should just stop helping.... – JustMeToo Nov 13 '14 at 19:13