Array[count+1] legal?

I get weird decimal digits when I run the program below.

  int coe_amount;

     cout << "How many coefficients exist in your term? ";
     cin >> coe_amount;

     float coefficient[coe_amount];

     for (int count = 0; count < coe_amount; count ++) 
                {            
                     cout <<    "Enter the coefficients of your variables, for term " << count << ": ";
                    cin >> coefficient[count];
                }

     for (int count = 0; count < coe_amount; count ++) 
                    {
                        
                        cout << coefficient[count+1];

                        cout << coefficient[ count];
                    }

It might have something to do with coefficient[count+1], which I don't know if it is a legal statement.

Basically I want the "coefficient[count+1]" to print the list of array elements that is one subscript ahead of coefficient[ count], for
"count < coe_amount" times. Is this how you do it? If not can somehow show me the correct syntax?

On the very last loop, [count+1] will go beyond the end of the array. So make your loop one shorter.

Also, this is not legal:

float coefficient[coe_amount];

...or rather, is legal only in a few very new and specific revisions of C/C++ which you might not have. Do this instead:

float *coefficient=new float[coe_amount];
1 Like

count+1 is legal but you should stay within the defined range 0...coe_amount-1.

1 Like

I haven't run into any trouble just doing:

int amount;

cin >> amount;

float number[amount];

I guess I am safe from doing this? It's more intuitive to me.

Not really, no. Variables are supposed to have their size fixed at compile-time, not runtime. I've had to fix lots of code where people have done things like that. It happened to work for them by sheer coincidence but compile it on a different system and it crashes.

If you tell a C compiler to do something crazy, it will do so, and not always complain, but might not do what you actually wanted. Don't trust that code is "right" just because it "works".

1 Like