Thursday, July 9, 2009

Easy C++ array help?

How to I set all of the values of an array (the size of the array depends on user input) to 0. I currently have (as an example):





int Array[i] = {0, 0, 0, 0};





where i is the size of the array, entered earlier.


Obviously this only works when i = 4. How could I do this so it will work whatever i.





Thanks for your help, and please try to use as simple language as possible to explain, as I have been programming for about a week :p

Easy C++ array help?
for (int j = 0; j%26lt;i; j++)


Array[j] = value;
Reply:There are as many ways as there are programmers to answer this question.





In CPP look at the new operator for an array object. Typically there is a set operator for the range of the array object. Depends on the package.





In standard C which is what you are asking:





#define MY_SIZE 20 // or any positive number


int some_array[MY_SIZE];








// first variable is the memory of the array


// second variable is the size of memory allocated


// the third variable is the value you want to initialize the array elements to





void initMyArray(int *array, int size, int InitValue)


{


int i;


for(i=0;i%26lt;size;i++)


array[i] = InitValue;


}





void main()


{


initMyArray(%26amp;some_array[0], MY_SIZE, 0);


}





Hope that helps
Reply:Check out http://www.pscode.com for great samples.
Reply:i wish i could learn c++


=(


!!!!
Reply:// use the dynamic array





int *my_array;


my_array = new int[array_size];





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


the_array[i] = i;





/*where (i) is the required value for the array items it can be any formula(2i+1,-1, ... etc.) */


No comments:

Post a Comment