Passing an array to a function and then changing the values?
Basically, let's say I declare an array in int main() and then pass it to another function, can i then change what values the array holds? Something like:
int main()
{
myarray[3] = {4, 5, 6};
myfunc(myarray);
return 0;
}
int myfunc(int开发者_Go百科 myarray[])
{
int x
cout << "Choose a number";
cin >> x
if (x == 1)
{
myarray[] = {0, 1, 3}
}
else
{
some code
}
return 6;
}
This code obviously does not compile, but I can't really think of any other ways to change the values in the array within the function.
You can modify elements in the array however initializer lists like this:
myarray[] = {0, 1, 3}
can only be used when you declare the array. To assign to the array you will have to assign each element individually:
myarray[0] = 0;
myarray[1] = 1;
myarray[2] = 3;
With the existing function signature there's no way to safely change the values. Normally you 'd do something like
myarray[0] = 0;
myarray[1] = 1;
//etc
There are many other ways to approach this as well, depending on how the values to go into the array are stored (either std::copy
or std::generate
might be handy here). But right now you don't have a way to know where the array ends.
To amend this, you need to pass the length of the array to the function somehow. One way is to simply pass an additional size_t length
parameter. An arguably better way that works in the spirit of C++ iterators is to write the signature like
int myfunc(int* begin, int* end);
and call it with something like
myarray[3] = {4, 5, 6};
myfunc(myarray, myarray + sizeof(myarray) / sizeof(myarray[0]));
if (x == 1)
{
myarray[] = {0, 1, 3} // {0,1,3} is an initializer list.
}
Initializer lists are allowed only at the point of declaration. They are not allowed in assignments. And in the if statement, you are doing an assignment. The only way of modifying the array elements is by changing element at each index in the if
.
myarray[0] = 0;
myarray[1] = 1;
myarray[2] = 3;
This: myarray[] = {0, 1, 3}
- is wrong.
You should pass the length of the array, and run a loop that would change its values, instead.
You should never assume a size of the array you get in a function. If the size is constant - make it myfunc(int myarray[THE_SIZE])
, otherwise it has to be myfunc(int myarray[], int size)
, where size
is the size of the array passed.
精彩评论