making a number sequence

Aug 18, 2011 at 12:09pm
con anybody tell me where is the error statement below? it, sequencing numbers but it will not run properly..
#include <iostream>
using namespace std;
int B ;
int main ()
{
cout << "insert the number of the sequence " ; cin >> B;
cout << "Number of sequencen " << B <<endl;
int A[B];

cout << "input values "<< endl;
int j, k, C, tmp;
for (C=0; C<B; C++)
{ cout << "A["<<C<<"] = "; cin >> A[C];}
cout << " values are " << endl;
for (C=0; C<B; C++)
{cout << "A["<<C<<"] = " << A[C]<< endl;}
// sequencing the data
for (j = 0; j < B; j++)
{
for (k = B ; k < B; k++)
{
if (A[k] > A[k+1])
{ tmp = A[k]; A[k] = A[k+1]; A[k+1] = tmp;}
}
}
cout << "the sequence are "<<endl;
for (C = 0; C < B; C++)
{cout << "A["<<C<<"] = " << A[C]<< endl;}
return 0;
}
Aug 18, 2011 at 12:48pm
Take a look at your second 'for' loop:

for (k = B ; k < B; k++)

That's not going to do anything.
Aug 18, 2011 at 1:25pm
ohh.. haha its my error.. hehe
but after that.. I compiled the code.. then there are some errors again.. it says:
Error 1 error C2057: expected constant expression
Error 2 error C2466: cannot allocate an array of constant size 0
Error 3 error C2133: 'A' : unknown size

I am using visual studio 2008 in win 7 64 bit
but, when i compiled it in devC++, it runs properly

Aug 18, 2011 at 2:32pm
I guess you'll have to use the 'new' operator, since you want to allocate the size dynamically:

http://www.cplusplus.com/doc/tutorial/dynamic/

So your code should look something like:

1
2
int * A;
A = new (nothrow) int [B];


That 'new' operator gives you a pointer to the memory it assigns, so after that you can use the array in exactly the same way that you did before, except that at the end you'll have to include:

delete[] A;

Or you'll end up with a memory leak.
Topic archived. No new replies allowed.