Home > Mobile >  array n shifting in c memory behavior
array n shifting in c memory behavior

Time:11-30

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?

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • c
  • Related