A
A
alex4answ2019-01-22 18:33:14
C++ / C#
alex4answ, 2019-01-22 18:33:14

Why does the function change the value of the passed variable?

Good afternoon, I can't understand something at all.
there is a function:

void shift(int a[], unsigned size, int shift) {

  for (int j = 0; j < shift; j++) {
    int tmp = a[size - 1];
    for (int i = 0; i < size; i++) {
      int current = a[i];

      a[i] = tmp;
      tmp = current;
    }
  }
}

It shifts the array cyclically, that is:
int a[5] = {1, 2, 3, 4, 5};

unsigned size = 5; // просто чтобы было удобно показать здесь.

shift(a, size, 2); // в жизни я не передаю размер массива абсолютным значением

As a result, the passed array is changed, not its copy, but the array itself, why?
I guess that the point is that the array is not just a variable, but an object, and when we pass it to a function, we do not pass a copy of it, but a reference to the object, even when we do not use pointers, am I right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pfemidi, 2019-01-22
@alex4answ

Yes, that's right, not a copy of the array is passed, but a pointer to the original. Naturally, the original also changes.

D
Daniil Demidko, 2019-01-22
@Daniro_San

The point is that in C++ you can't pass an array by value. When you write void f(int arr[]), it's the same as void f(int *arr).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question