1D array problem

Hi Everyone!
i have a small program here,i let the user choose the size of the 1D array and it's elements and if they want to print it they should press 1.. now the problem is whenever i run the program for loops don't run as intended and i get weird outputs.. what is wrong ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
int main()
{
    int a[0];
    int c;
    int k,j,size;
    
    cout<<"enter the size of the array \n";
    cin>>size;
    for(k=0; k<size;k++)
    {
        cout<<"enter the element "<< k + 1<<endl;
        cin>>a[k]; 
    }
    cout<<"to print the array press 1 \n";
    cin>>c;
    if(c == 1)
    {
    for(k=0;k<size;k++)
    {
     cout<<a[k]; 
     cout<<" ";
    }
  }
    return 0;
}
Last edited on
Change line 5 to
int a[10000];
and that should keep you going for a while.

Later, you can go and look up vectors.
int a[0]; creates an array with zero elements in it, and no way to change the number. You are getting "weird output" because you are going out of bounds no matter what size the user chooses.

Your compiler should give you a warning you are out-of-bounds with the array.
Topic archived. No new replies allowed.