Help with setting all elements of array to 0

Hi,

I'm trying to set all the elements of my array to 0 but nothing seems to be working. Could greatly use some help. Thanks!



.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef ServerGroup_h
#define ServerGroup_h

class ServerGroup 
{
  
public:
  ServerGroup(const int&); 

private:
  int *servers;

};

#endif  



.cpp
1
2
3
4
5
6
7
8
9
10
ServerGroup::ServerGroup(const int& numArray) 
{
  size = numArray; // number of elements in the array
  

  servers = new int [numArray]; // pointer to numArray
  size = numArray; // size = elements in the array

}


I want to set each element of the array in servers to 0 based on what is passed into size by numArray.

Lines 3 and 7 do the same thing in your cpp code, and where is size defined in your header?
both vector<int>(numArray) and new int[numArray]() will set them all to zero. Any specific reason you want to use new[] instead of a vector?
Thanks and we can't use vector yet because our textbook hasn't covered vectors yet. We have only just been introduced to "new". Ah and yes sorry about lines 3 and 7 being the same. I was playing around with my code and didn't realize I copied and pasted something twice in different places. Good eye!
Would new int[numArray]() be doing the same thing as this for loop?

Basically I just want to set servers to 0.
1
2
3
4
5
6
7
8
9
ServerGroup::ServerGroup(const int& numArray) // set # elements in dynamic array
{
  servers = new int[numArray];
  size = numArray;
  for(int i = 0; i < size; i++)
  {
    servers[i]=0;
  }
}


vs

1
2
3
4
5
ServerGroup::ServerGroup(const int& numArray) // set # elements in dynamic array
{
  size = numArray; // num elements in array
  servers = new int [numArray](); 
}
Last edited on
yes, servers = new int[numArray](); sets all servers to 0. It's when you need initial values other than zero when you need a loop (or, more typically, a vector)
Thanks! So in this case the easier and cleaner code would be to simply use servers = new int [numArray](); then?

I'll use that over the for loop. Thanks
The easier and cleaner code involves using std::vector ;)
Last edited on
well, in the case of you're using a simple array, you can use the fill function contained in the algorithm library, or simply you can use the iterator method -- for(i = 1 -- N) arr[i] = 0, you can create a new instance of the array, or you can use the data structure vector<Object>

the structure of fill is just like this:
fill(array+1, array+N+1, 0);

regards and good luck ;)
cbretana wrote:
the structure of fill is just like this:
fill(array+1, array+N+1, 0);
Where did you come up with this? This will not only skip the first element in the array but also corrupt memory after the array.
Topic archived. No new replies allowed.