Strange array problem

Hi there,

I have a strange problem with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
    const int arraySize = 19;

    double degTheta[ arraySize ];

    // Initialise array degTheta
    for ( int i = 0; i < arraySize; i++ )
    {
        degTheta[ i ] = i * 5.0;
        cout << degTheta << endl;
    }


    return 0;
}


It ouputs a weird answer (0x22fe80), instead of

0
5
10
... all the way up to 90

How do I fix this problem?

Thanks :)

line 14:
 
cout << degTheta[i] << endl;


an array name without brakets (ie: "degTheta" instead of "degTheta[i]") returns a pointer to the array. That's why you're getting a funky address printed.
Last edited on
Besides that, you are making an array that has a variable as the number of elements:

 
double degTheta[ arraySize ];


This is bad.It is not allowed in C++, in C it is, but C doesn't have vectors, so they needed something similar too.Unfortunately, the compiler will allow this.It won't give a error.But even if it works sometimes, othertimes you will get an error.Do not use this way of declaring an array.You should specifically put the number of elements that the array has, like:

 
double degTheta[10]; // the array has 10 elements 


If you want array of variable length, use vectors.
Besides that, you are making an array that has a variable as the number of elements:

double degTheta[ arraySize ];

This is bad.It is not allowed in C++, in C it is, but C doesn't have vectors, so they needed something similar too.


It's BAD... WHY???? I always thought that it is a good practice to use a constant variable as the array size. If he would not have used a constant variable, then it would have been bad.

But even if it works sometimes, othertimes you will get an error.

This will work everytime. I don't see a reason as why it will not work. Could you please give an example of a scenario when it is declared as a local variable and not working?
andrei c is confusing something. using a variable would be non standard but using a const is fine
using a variable would be non standard but using a const is fine


Exactly !
Last edited on
Sorry, you are wright. I just looked and saw a variable and out of istinct i assumed it is just a variable not a const variable.
Last edited on
Topic archived. No new replies allowed.