1

Ok so last night I taught my sister some basic code how to read input, put it in array and print it to the screen. Here is the code :

int main() {
    int N;  // size of array

    cin >> N;
    int arr[N];

    for(int i = 1; i<= N; i++) {
        cin >> arr[i];
    }

    for(int i = 0; i<N; i++) {
        cout << arr[i] << endl;
    }

    return 0;
}

And here is the result :

input :
4
2 3 4 1

output :
8
2
3
4

I don't have any clues why this can happen, I tried to check the code but it seems simple and already correct for me.

4
  • 6
    array-indices start with 0, not 1. Commented Jul 2, 2016 at 15:33
  • 2
    Variable length arrays are not standard C++ and not portable. I'd suggest using a std::vector instead. Commented Jul 2, 2016 at 15:36
  • Stay away from the variable length arrays. Use std::vector instead. Using std::vector not only makes your program standard C++, you have the chance to check your own errors like this using at(). Commented Jul 2, 2016 at 15:59
  • Thanks, I realize the mistake now, how silly of me Commented Jul 2, 2016 at 16:33

4 Answers 4

4

First of all C++ does not support variable length arrays and if an array is declared as having N elements then the valid range of indices is [0, N-1].

You could either dynamically allocate an array of the required size yourself or use standard container std::vector<int>.

Using std::vector<int> you could for example write

#include <iostream>
#include <vector>

int main() 
{
    unsigned int n = 0;

    std::cout << "Enter number of elements: ";
    std::cin >> n;

    std::vector<int> v( n );

    std::cout << "Enter " << n << " elements: ";

    for ( int &x : v ) std::cin >> x;

    std::cout << "\nThe array is ";

    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

The program output might look like

Enter number of elements: 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9

The array is 0 1 2 3 4 5 6 7 8 9 
Sign up to request clarification or add additional context in comments.

Comments

3

The first thing you have to look after is that dasblinkenlight has already mentioned in his answer, variable-length arrays are a language extension.

Then you should think that arrays are zero index based. What does this means? Let's consider an array of size 4 that is denoted as arr. Then it's elements can be accessed as arr[0], arr[1], arr[2], and arr[3]. So what happens when you run your first loop?

for(int i = 1; i<= N; i++) {
    cin >> arr[i];
}

You set the a value for arr[1], arr[2] to arr[N]. But the arr[N] points to a place in memory that is not associated with the array, since the array's size is N and all arrays are zero based. The last element of the array lives in here arr[n-1].

Unfortunately in C++ there isn't any check for the length of an array and you are allowed to do things like this. For instance, if you had tried this in C# or in Java then you would have got an Index Out Of Range Exception.

If you change your code to the following, then you will get the expected output:

for(int i = 0; i<N; i++) {
    cin >> arr[i];
}

for(int i = 0; i<N; i++) {
    cout << arr[i] << endl;
}

2 Comments

in C++ there isn't any check for the length of an array and you are allowed to do things like this. For instance, if you had tried this in C# or in Java then you would have got an Index Out Of Range Exception. Plain arrays, sure. But if the OP wanted to protect against stuff like this during development, they could use std::array and index using .at(i), which would throw exactly that kind of exception. Or, better, use a 'debug mode' version of std::array as in various compilers, which checks on operator[], so you don't have to s/\.at(\(\d*\))/[\1]/g on release, as we usually should
I should clarify that everything I said above also applies to std::vector, which can be thought of as the dynamically sized equivalent of std::array and so, as Vlad and PaulM have noted, is probably more relevant here.
2

Your code is not valid C++, because variable-length arrays are a language extension.

With that part out of our way, consider what happens in your first loop's last step: you are accessing an element past the end of the array, which is undefined behavior.

Your second loop is correct, though, so all you need to do is correcting the header of the first loop to match the header of the second loop.

Comments

0

An array of N elements has indexes from 0 to N-1 (so: N-1 - 0 + 1 = N elements, some maths.)

So fix this: for(int i = 1; i<= N; i++) with this : for(int i = 1; i< N; i++)

1 Comment

This assumes the OP doesn't want to cin to arr[0], which context suggests is false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.