3

I made a code in which I had to take the size of an array as the user’s input and its elements too and print them.

#include <iostream>
using namespace std;
 //Compiler version g++ 6.3.0

 int main()
 {
     int i;
     cout<<"\nenter the size of array";
     cin>>i;
     int n[i];
     for(int j=0;j<=i;j++)
     {
         cout<<"\nn["<<j<<"]=";
         cin>>n[j];
     }
     for(int k=0;k<=i;k++)
     {
         cout<<endl;
         cout<<"\nn["<<k<<"]=";
         cout<<n[k];
     }
 }

Suppose in the following: The value of i is 3 (according to user’s input). In the first loop the condition for j is up to <=i where i is the size of array (this shouldn't happen as i begins from 0) due to which the Compiler asks me to input 4 values for the array (n[0], n[1], n[2] and n[3]) but the size of the array is 3 only. How can it store 4 objects?

Melebius
  • 6,183
  • 4
  • 39
  • 52
meispi
  • 63
  • 2
  • 6
  • 2
    As arrays begin with 0 the last element has index n - 1. Hence, loops in C++ (and C) usually terminate with condition `i < n`. – Scheff's Cat Nov 29 '17 at 10:09
  • 1
    In C++ you can write outside the bounds of an array, you should never do that because it's undefined behavior. but it's possible! – xander Nov 29 '17 at 10:10
  • 5
    Btw. `int n[i];` is a VLA (variable length arrays). VLAs are optionally supported in C11 but not in C++. If your compiler supports this it is a non-standard extension. Better: Use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) instead of VLA. – Scheff's Cat Nov 29 '17 at 10:11
  • 1
    `int n[i];` is not valid C++ but a gcc's extension. Don't use extensions, compile with `-std=c++17 -pedantic -Wall`. – n. m. could be an AI Nov 29 '17 at 10:13
  • @xander sir if that is so Then what is the use of size in arrays – meispi Nov 29 '17 at 10:21
  • 2
    The size in arrays is to express the number of elements an array has @user8640354. The problem here is that size is a variable. In such cases we use dynamic allocation of arrays (in C for example) and `std::vector` in C++. Read more in my answer. – gsamaras Nov 29 '17 at 10:33
  • @gsamaras sir can you explain how can I use in this case – meispi Nov 29 '17 at 10:42
  • I included an example in my answer. – gsamaras Nov 29 '17 at 10:55

2 Answers2

3

Change this:

for(int j=0;j<=i;j++)

to this:

for(int j = 0; j < i ; j++)

since array indexing ends at the size of the array minus 1. In your case i - 1.

Likewise, you neeed for(int k=0;k<i;k++).

Your posted code invoked Undefined Behavior, by accessing the array out of bounds.


This:

int n[i];

is a Variable Length Array (VLA), which is not Standard C++, but is supported by some extensions.

and if you compiled with pedantic flag, you would get:

prog.cc: In function 'int main()':
prog.cc:9:9: warning: ISO C++ forbids variable length array 'n' [-Wvla]
  int n[i];
         ^

If you want something like this data structure, then I suggest you use an std::vector instead, which is Standard C++.


By the way, it's not a syntax error or something, but i is usually used as a counter (like you used j), an index if you like. As a result, I would chnage it's name to size, for instance, or something related.


EDIT:

Example with std::vector and variable renaming:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int tmp, n;
    cout<<"Input number of elements\n";
    cin >> n;
    vector<int> v;
    for(int i = 0; i < n; ++i)
    {
        cin >> tmp;
        v.push_back(tmp);
    }
    for(auto number: v)
        cout << number << endl;
    return 0;
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

You need to check for less than i and not less than equal i. Otherwise it will try to store value for 0,1,2,3 in that case the last object will cause memory corruption. In c++ it will not give you any error even if you try to add 100 members in array of size 3.

It better you read memory management in c++ before jumping into coding.

CodeJunkie
  • 113
  • 1
  • 11
  • Then what's the use of size if even the array of size 3 can contain 100s of members – meispi Nov 29 '17 at 10:16
  • @user8640354 No, an array of size 3 cannot _contain_ hundreds of members. However, you can write them _past_ the array until someone notices it (debugger, OS) – that’s called [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). – Melebius Nov 29 '17 at 10:21
  • That what the difference between add and contain. You can add but that will result in undefined behaviour as describe by Melebius. You might not even get error while debugging as it might not corrupted any memory worthwhile. – CodeJunkie Nov 29 '17 at 10:32