If I have the following in C:
void increment_ptr(int *arr_ptr)
{
int i;
for(i=0; i<10; i++)
{
arr_ptr++;
}
}
int main()
{
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int *arr_ptr = arr;
increment_ptr(arr_ptr);
}
Am I right in thinking that when I return to main after calling increment_ptr, arr_ptr is still pointing to arr[0]?
Yes
Because you call the function like this:
increment_ptr(arr_ptr);
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 in the same memory location arr(&arr[0]). Modifying arr_ptr from the function increment_ptr won't affect arr_ptr in main.
For modifying arr_ptr in main from increment_ptr, you need to pass the address of arr_ptr to increment_ptr which is an int**(pointer to pointer to int)
Yes, that is correct. Functions can modify pointees, but not pointers, so to speak, since we're passing everything by value. If you want to modify arr_ptr, you need a pointer to a pointer, like so:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With