Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array to function

Tags:

arrays

c

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]?

like image 817
jramm Avatar asked Sep 26 '26 04:09

jramm


2 Answers

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)

like image 125
Spikatrix Avatar answered Sep 28 '26 20:09

Spikatrix


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)