Chris_45
Chris_45

Reputation: 9043

Zero out array sent as parameter in C++

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

int myArrayFunction(int p_myArray[]) {
p_myArray[] = {0};//compiler error syntax error: ']'
.
.
}

Upvotes: 1

Views: 525

Answers (7)

Hernán Eche
Hernán Eche

Reputation: 6899

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.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170499

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

Upvotes: 1

Uri
Uri

Reputation: 89749

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).

Upvotes: 0

Billy ONeal
Billy ONeal

Reputation: 106549

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);
}

Upvotes: 0

bakkal
bakkal

Reputation: 55448

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

Upvotes: 0

kennytm
kennytm

Reputation: 523304

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);

Upvotes: 9

Etienne de Martel
Etienne de Martel

Reputation: 36851

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

Upvotes: 0

Related Questions