Tuesday, July 28, 2009

C++ question?

How can I have the user enter a number and have that number become the size of the array?





for example (where the number will be "x":





cout %26lt;%26lt; "\nHow many numbers (up to 4) would you like to input? " %26lt;%26lt; endl;


cin %26gt;%26gt; x;


cout %26lt;%26lt; "\nPlease input up to 4 numbers now: " %26lt;%26lt; endl;


cin %26gt;%26gt; f %26gt;%26gt; b %26gt;%26gt; c %26gt;%26gt; d;


const int arraySize = x;


int a [ arraySize ] = { f, b, c, d };


int i, hold;





it gives me the error that the arraysize must be a constant number.





does anyone know?

C++ question?
You say "int *a = new int[arraySize];" and then assign the values instead of "int a[arraySize] = . . ."





This use of the "new" operator is called "dynamic array allocation".
Reply:as others have pointed out, a memory can only be allocated with a constant number.





(this is actually no longer true, the newest C standard allows a[arraySize] as well, but most likely your compiler has not implemented it).





if you allocate an array with new[], don't forget to release it with delete[].





int *a=new int[arraySize];


a[0]=1;


a[1]=2;


// etc


delete[] a;
Reply:x is a variable in its mind, so it will not accept it. to have the array you need to have a constant in the array size, espically with the const int arraySize=x;. I am not totally fimilar with c++ but if you could change the const to a word indicating a variable, it may work.





hope this helps

sweet pea

No comments:

Post a Comment