0

I am going through a cpp course and the instructor used the following notation to get a subarray of the current array

void f(int arr[], int len) {
    if (len == 0)
        return;
    f(arr + 1, len - 1); // arr + 1 takes a subarray 
    ...
}

I wanted to understand how the arr+1 notation works with regards to memory. Arrays are passed by reference, but when you arr + 1 is a copy of the array from the provided offset created, or does it simply advance some pointer and no extra memory is used?

Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59
  • 1
    `arr` is a pointer to the array. So think in terms of pointer arithmetic. – kiner_shah Nov 30 '21 at 04:02
  • 1
    `arr` is only a pointer, and it is passed by value. so no array copy happens here. – Nimrod Nov 30 '21 at 04:15
  • Thanks all, I realized array is passed by reference, but didn't think of the implication until you all mentioned that it is just a pointer and "arr + 1" is pointer arithmetic. – Jeremy Fisher Nov 30 '21 at 04:22
  • 1
    [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) It starts off as an array, and an array is not a pointer, but as soon at you call that function, Whammo! Array decay. – user4581301 Nov 30 '21 at 04:24

2 Answers2

1

This is generally avoided in c++, but for learning purposes

arr + 1 is arr starting from the next element in the array. For example

char arr[] = "12345";
printf("%s\n", arr + 1); //prints 2345

Pointer arithmetic applies, pointer is passed to printf. Note that strlen(arr) is 5, while strlen(arr + 1) is 4, this is where you get len - 1

*(arr + 1) is same as arr[1] For example

printf("%c\n", *(arr + 1)); //prints 2
printf("%c\n", arr[1]); //prints 2

Similar notation with integer arrays

int arr[] = {0,1,2,3,4};
printf("%d\n", *(arr + 1)); //prints 1
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
  • Thanks! Yeah the missing piece for me was that `arr + 1` means move the pointer by 1. Therefore, since it's just passing a value of a pointer + 1, it's not a full array copy, which is what I was worried about, and thus no real extra memory used beyond the pointer + 1 value. – Jeremy Fisher Nov 30 '21 at 04:27
  • Yes it's seen as `(pointer + 1)`, pointer arithmetic applies, and "array to pointer decay" as mentioned in the other answer and earlier comments. – Barmak Shemirani Nov 30 '21 at 04:48
0

array is pass by pointer when you call in function see this