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: ']'
.
.
}
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: ']'
.
.
}
With a loop. Which means you'll also need to give the array's size to the function.
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);
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.
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 data to flag the end.