Sunday, July 12, 2009

User declaring the size of the array in c++??

is it possible to let the user input the size for an array in c++? thx

User declaring the size of the array in c++??
Yes, but you need to dynamically allocate the array. This is done by creating a pointer and then assigning a specific amount of memory to that pointer.





int size = 0;


cin %26gt;%26gt; size;





int *a = null; //could use any data type


a = new int[size];





There you go... now 'a' can be accessed just like a normal array. It is important to note that you should delete the dynamically allocated array before the program exits. To do this:





delete a[];





Then assign the pointer to a null value:





a = null;





Hope this helps.
Reply:i tried this part





int size = 0;


cin %26gt;%26gt; size;





int *a = null; //could use any data type


a = new int[size];





but i receive the error - 'null' : undeclared identifier.


so what did i do wrong, thank you Report It

Reply:Duncan is correct in his answer, but you may want to put in a range check so that the user cannot specify a negative number or an unusually large value.

buy flowers

No comments:

Post a Comment