Tuesday, July 28, 2009

How do you initialise an array in C++ when you dunno its size?

My program keep getting run-time error so can someone give me a few lines of sample code?

How do you initialise an array in C++ when you dunno its size?
If you wanted to write an initialization function for an array of integer, you might try this:





void arrayInit(int *a) {


for (int i = 0; i %26lt; ???; i++) {


*a++ = 0;


}


}





But arrayInit doesn't know the size of the array, so you have a problem. Don't give up there and say it can't be done. In C++ you have some options.





You could define a template type for your array:





template%26lt;typename T, size_t Size%26gt;


struct array { T val[Size]; };





Then you can write a generic array initialization function:





template%26lt;typename T, size_t Size%26gt;


void init(array%26lt;T,Size%26gt;%26amp; a) {


for (size_t i = 0; i %26lt; Size; i++) {


a.val[i] = 0;


}


}





Declaration of an array of 10 ints looks like this:


array%26lt;int,10%26gt; myIntArray;





Then you can call the init function:


init(myIntArray);





A more likely option for a generic array of type T in C++ is to use vector%26lt;T%26gt;. An easy way to initialize your vector object is to call its erase operation.
Reply:one drawback with an array is you must know the size.





arrays start allocating space with 0. so if you have an array you want to initialize 5 spots with 0, you need to put it in a loop. for example





int array[4];


for (int i=0, i %26lt; 5; i++)


{


array[i] = 0;


}
Reply:Some tips are given you, but source codes. Because We woud not like our lazy future progrmmars.


My dear ! At time of defining a variable, initialize it.


like:


abc [x][x][x]





Also check your programm again . It may have a syntax error.


O K

pansy

No comments:

Post a Comment