Question:
c++ default an array to 0 using a function?
anonymous
2008-04-17 18:26:31 UTC
trying to set all elements of an array to 0. Tried using this function:

void array::zeroOut()
{
array[20] = {0}; // Set array to Zero
}

but I get a syntax error saying:

expected primary-expression before '{' token
expected `;' before '{' token

for line:

array[20] = {0};


I think it has something to do with the brackets in the assignment statement, but I have no clue. Any ideas?
Four answers:
anonymous
2008-04-17 20:38:38 UTC
(1) Normally the line



array[20] = {0};



is fine when you *declare* the array and initialize it in a function. The entire array will be set to zeros. But you can't do that if array is a data member of a class, as your method signature would suggest.



(2) In the context of



void array::zeroOut()

{

array[20] = {0}; // Set array to Zero

}



the compiler thinks you are trying to change the value of the 21st element and the proper syntax would be



array[20] = 0;



But, of course, since your array has only 20 places and you are trying here to change the 21st you are going to have other issues.



(3) The simplest thing to do is just write a for loop like



for (int i = 0; i < 20; i++)

array[i] = 0;
Broken M
2008-04-18 01:40:50 UTC
when setting it with brackets {}, you need to declare each one such as:



array[20] = {0, 0, 0, 0, 0, 0, 0...}



I would suggest that you use a for loop to set all to zero:

for (int i = 0; i <= 20; i++) {

array[i] = 0;

}



by the way, remember that the array commences with 0, so you would declare it as array[19], which in turn would hold 20 spaces from 0 through 19.
closetgeek
2008-04-18 01:45:43 UTC
Umm... why all the negative attention??



int's are always the same size (most often 32 bits) and would have the sizeof() 4. They can also be 64 bit though, so it is best to figure the length dynamically. the difference is based on the word length of the processor not the value of the element. each element will have the same bit length no matter its value. That means



total_bits / bits_per_element



will result in total elements... or the length of the array



int i;

int array_length;



array_length = sizeof(array)/sizeof(array[0]);



for (i = 0 ; i < array_length ; i++ )

{

array[i] = 0;

}
anonymous
2008-04-18 01:43:46 UTC
You need to set each entry of teh array to zero with a loop. Also, you need to pass in the array, like this:



http://xoax.net/comp/cpp/console/Lesson18.php


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...