2

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?

5 Answers 5

1

There are many ways to do it:

  1. If you are using C++11, use std::array.
  2. Use std::vector<int> to pass array. You can modify local copy and argument array won't change.
  3. If you want not to modify value, pass it as const * or const reference to array. For ex const int *arr or const int (&arr)[10]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

You can make the parameter const if you don't want to change its values:

void func( const int * intArray, size_t size) {...}

2 Comments

Would you not pass it as a const ref though? If all you're doing is reading from the array etc?
Actually, ignore me, just spotted it. Sorry about that. Totally forgot you have an array of ints like that the same way you can do char*....sorry for confusion
0

or you can write something like this:

void func (const int array[10])
{
   // you can work with you data here withot changing an array
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.