Skip array to work

If in C:

void increment_ptr(int *arr_ptr)
    int i;
    for(i=0; i<10; i++)

int main()
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
    int *arr_ptr = arr;



Am I getting it right that when I return to main

after the call increment_ptr

, arr_ptr

still points to arr[0]



source to share

2 answers


Because you are calling the function like this:



This passes a copy of the pointer (pass-by-value). arr_ptr

in increment_ptr

is different from arr_ptr

in main

, although both point to the same memory location arr

( &arr[0]

). Changing the arr_ptr

function increment_ptr

will not affect arr_ptr

c main


To change arr_ptr

to main

from, increment_ptr

you need to pass the address arr_ptr

to increment_ptr

, which is int**

(pointer to pointer to int




Yes, that's right. Functions can change pointers, but not pointers, so to speak, since we pass everything by cost. If you want to change arr_ptr

, you need a pointer to a pointer, for example:

static void set_to_null(int** arr_ptr)
    *arr_ptr = 0;

int arr[] = {1, 2, 3, 4, 5};
int* arr_ptr = arr; // arr_ptr stores address of 'arr'
set_to_null(&arr_ptr); // arr_ptr now stores 0 (null)




All Articles