Arrays

I'm working on a program and this is my first time using arrays. This part of the code is fairly self explanatory. I've been trying to play around with data types for the array because I keep getting weird output values depending on the date type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  int i;
        double p[i];
        
        for (i=0; i<5; i++)
        {
           cout<<"Input hours driven: ";
            cin>>y;
            p[i]=y;
        }
        for (i=0; i<5; i++)
        {
        cout<<p[i]<<endl;
        }

If I assign it as a double, and input 5 '1', this is my output:
1
1
6.95324e-310
6.95324e-310
1
However if I define it as float, my output is this:
1
1
1
1
4.18829e+32
Float won't hold anything passed 4 values properly.
I can't use int because these eventually will have decimal places.
Why is this happening? How do I go about fixing this?

Also, I'm on a Mac using XCode.
Line 1: i is an uninitialized variable. It contains garbage.

Line 2: It's not legal C++ to dimension an array with a non-const variable. Some compilers do allow this as a non-standard extension, however, how big do you think the array is if i is garbage?


Last edited on
I see. That makes sense.
The reason I wrote it this way is because 5 is actually supposed to be another variable z which is defined with user input earlier in the code. So in this case, would I just dimension it with a maximum value, say,
double p[20]; ?
Or is there a more correct way to do this sort of thing?
Last edited on
Using 20 is fine if you edit check that z is no bigger than 20.

The preferred way to do this is with std::vector. A std::vector will allow your array to be any size.
http://www.cplusplus.com/reference/vector/vector/

You can also use dynamic memory.
1
2
3
4
5
6
 
  double * p;

  p = new double[z];  // z is legal here 
//  do something
  delete [] p;  // Be sure to delete to prevent a memory leak 


Topic archived. No new replies allowed.