I want to do something with array A in function B. In function B, some value of A is changed. I know that because A is a pointer so its values will be changed after B is executed. So that I have to use C which is a copy of A to make sure that A aren't changed after B is executed.
I am wonder that is there any other way that I don't have to use the array C?
如果不想更改其值,可以将其设置为const
:
void func( const int * intArray, size_t size) {...}
There are many ways to do it:
std::array
. std::vector<int>
to pass array. You can modify local copy and argument array won't change. const int *arr
or const int (&arr)[10]
or you can write something like this:
void func (const int array[10])
{
// you can work with you data here withot changing an array
}
If you want to pass a pointer to an array and you want to make sure that the array content is not modified inside the function, you can use const
:
void DoSomething(const int * data, size_t size)
In C++, you may want to consider a container class like std::vector
, and you can pass it using a reference to const
(to avoid useless and potentially expensive deep-copies of vector):
void DoSomethingCppStyle(const std::vector<int>& data)
Note that in this case there is no need to pass a size parameter separately, since std::vector
knows its own size (returned by std::vector::size()
).
It's not possible to pass an array by value in C++.
You either have to manually make a copy of it and "pass" that, or replace the array with a container that wraps an array such as std::array
or std::vector
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.