开发者

Zero out array sent as parameter in C++

开发者 https://www.devze.com 2022-12-26 15:27 出处:网络
How do you make all elements = 0 in the array sent as a parameter? int myArrayFunction(i开发者_Python百科nt p_myArray[]) {

How do you make all elements = 0 in the array sent as a parameter?

int myArrayFunction(i开发者_Python百科nt p_myArray[]) {
p_myArray[] = {0};//compiler error syntax error: ']'
.
.
}


No you can't. There's not enough information. You need to pass the length of the array too.

int myArrayFunction(int p_myArray[], int arrayLength) {
// --------------------------------------^ !!!

Then you can use memset or std::fill to fill the array with zero. (= {0} only works in initialization.)

    std::fill(p_myArray, p_myArray+arrayLength, 0);

Alternatively, switch to use a std::vector, then you don't need to keep track of the length.

int myArrayFunction(std::vector<int>& p_myArray) {
    std::fill(p_myArray.begin(), p_myArray.end(), 0);


Use std::fill_n(). You'll need to pass the number of elements.


With a loop. Which means you'll also need to give the array's size to the function.


int myArrayFunction(int p_myArray[], int size)
{
   for(int i=0; i<size; i++)
   {
      p_myArray[i] = 0;
   }
.
.
}


Use std::fill. You need to pass the size of the array to the function somehow. Here's an example using the template size method, but you should consider passing a regular size parameter.

template<size_t size>
int myArrayFunction(int (&p_myArray)[size]) {
    std::fill(p_myArray, p_myArray + size, 0);
}


That sort of assignment only works for the initialization of a new array, not for modifying an existing array.

When you get an int[], you essentially have a pointer to some area in memory where the array resides. Making it point to something else (such as a literal array) won't be effective once you leave the function.

The most you can do is update individual cells with the [] operator or with library functions. For example, p_myArray[i]=0 (you can do this in a loop on i but you will need to pass the size to your function).


If your p_myArray[] have a terminating character you can loop till that char is found. For example if it were a string as a null-terminated char array you will stop when find '\0'

int myArrayFunction(char p_myArray[])
{

   for(int i=0;p_myArray[i]!='\0';i++)
       p_myArray[i]=0;

   //..
}

if p_myArray, have numbers from 0 to 100, you can use the 101 to indicate the array end, and so on..

So analize p_myArray use and content, if it can have a value that will never be used as data, you can use it as terminating code to flag the end.

0

精彩评论

暂无评论...
验证码 换一张
取 消