-1

I'm a newbie and started to code couple of days ago. So today started with array and have some doubts. I'm reading a array by taking input from user and displaying it everything s running fine but on ouput screen I'm having a garbage value and dont know why. Please help me.

#include <iostream>
using namespace std;

int main(){
    int number;
    cout<<"Enter a array_size"<<endl;
    cin>>number;

    //Reading and printing array
    int array[number];
    int i=1;
    while(i<=number){
        cin>>array[i];
        i++;
    }
    //printing array
    int j=0;
    while(j<=number){
        cout<<array[j]<<endl;
        j++;
    }
}

Expected output: Reading from user: 3

1
2
3
//displaying
1
2
3

Actual result: Reading from user: 3

1
2
3
16
1
2
3

Why 16 is showing?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
NoobCodes
  • 17
  • 3
  • 6
    `int array[number];` -- This is not valid C++. Arrays in C++ must have their size denoted by a compile-time constant, not a runtime value. Dynamic arrays in C++ are done by using `std::vector`: `std::vector array(number);`. [See this](https://godbolt.org/z/Pv899Wfb1) – PaulMcKenzie May 17 '23 at 07:47
  • 3
    You are writing from index 1 and reading from index 0. Besides you are accessing one past the last element. Eventually, check PaulMcKenzie comment. – Oersted May 17 '23 at 07:48
  • Array indexes start at 0, not at 1. – Jabberwocky May 17 '23 at 07:49
  • [Arrays always start at zero](https://stackoverflow.com/questions/2289548/array-indexing-starting-at-a-number-not-0) and [**Accessing an array out of bounds gives no error, why?**](https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why) –  May 17 '23 at 07:53
  • Maybe I misunderstood your question: Is your actual question: _Why am I seing `16` instead of some garbage_? – Jabberwocky May 17 '23 at 07:54
  • Does this answer your question? [Accessing an array out of bounds gives no error, why?](https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why) –  May 17 '23 at 07:55
  • 1
    I'm curious where you learned that `int array[number];` (`number` is a variable) is legal C++? Wherever that is please be aware that it is not teaching you correct C++. – john May 17 '23 at 08:18
  • Do yourself a favour and forget that C-style arrays exist in the language and exclusively use [std::array](https://en.cppreference.com/w/cpp/container/array) & [std::vector](https://en.cppreference.com/w/cpp/container/vector) instead. – Jesper Juhl May 17 '23 at 08:19
  • Your code has [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub) due to indexing out of bounds. The compiler is not obligated to diagnose this, but it means that it is allowed to produce *any* result, including what you expect, something you did not expect, a crash, no output at all, etc - literally *anything* is allowed. C++ does not hold your hand. – Jesper Juhl May 17 '23 at 08:28
  • Print `i` during the first loop, and `j` during the second loop and consider the difference. – molbdnilo May 17 '23 at 12:18

4 Answers4

2

As mentioned in the comments, c++ does not support VLA (variable length arrays) - see here: Why aren't variable-length arrays part of the C++ standard?.

It was also already mentioned that array indices start at 0, not 1 (Array indexing starting at a number not 0).

You can avoid these issues using std::vector and ranged-based loops (the latter is available since c++11).

Code example for you case:

#include <iostream>
#include <vector>

int main()
{
    int number;
    std::cout << "Enter a array_size" << std::endl;
    std::cin >> number;

    // Read:
    std::vector<int> array(number);
    for (auto& elem : array)
    {
        std::cin >> elem;
    }

    // Print:
    for (auto const & elem : array)
    {
        std::cout << elem << std::endl;
    }
}

Note that auto elem : array (without &) would not have worked because auto by itself would not infer a reference and instead copy the element.

A side note: better to avoid using namespace std - see: Why is "using namespace std;" considered bad practice?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
0

There are 2 problems with your code.

First int array[number]; is not standard c++ as number is not a constant expression.

Second, array indices start as 0 instead of at 1 in c++.


There are also many other posts describing these problems.

Array index always start at 0

Why accessing out of bound array does not give any error

-1

The array should always start at index 0. Update your starting index and the conditions.

//Reading and printing array
int array[number];  
int i=0; // should start with zero.
while(i<number){  // should be less than only since you start with zero.
    cin>>array[i];
    
    i++;

}
//printing array
int j=0;
while(j<number){   // should be less than only since you start with zero.
    cout<<array[j]<<endl;
    j++;
}
  • 2
    This is not standard c++. Refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to learn more about arrays. –  May 17 '23 at 08:17
-2

Array indexes start at 0, not at 1.

Corrected code:

  //Reading and printing array
  int array[number];
  int i = 0;
  while (i < number) {
    cin >> array[i];
    i++;
  }

  //printing array
  int j = 0;
  while (j < number) {
    cout << array[j] << endl;
    j++;
  }

It's more idiomatic to use a for loop here:

  //Reading and printing array
  int array[number];

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

  //printing array
  for (int i = 0; i < number; i++) {
    cout << array[j] << endl;
  }
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115