LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C: Question on pointers (https://www.linuxquestions.org/questions/programming-9/c-question-on-pointers-4175476388/)

HMW 09-08-2013 01:30 PM

C: Question on pointers
 
Hi!

I have a small test program that looks like this:
Code:

void fill_arr(int *pointer, int size);


int main()
{
    int array[SIZE] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int *pointer;
    srand(time(0));
   
    pointer = array; // pointer = array[0]

    fill_arr(pointer, SIZE);
   
    /* Let's try and print the above... */
    int k;
    for (k=0; k<SIZE; k++) {
        printf("Array value %d: %d\n", k, array[k]);
    }

    printf("Address of pointer: %p\n", pointer);
    printf("Address of array[0]: %p\n", &array[0]);

    return 0;
}

void fill_arr(int *pointer, int size)
{
    int i;
    for (i=0; i<SIZE; i++) {
        *pointer = (rand()%10)+1;
        pointer++; // move index by one to array[1], array[2], etc...
    }
}

With the following output:
Code:

Array value 0: 10
Array value 1: 10
Array value 2: 7
Array value 3: 6
Array value 4: 7
Array value 5: 8
Array value 6: 6
Array value 7: 1
Array value 8: 6
Array value 9: 6
Address of pointer: 0xbfd9db20
Address of array[0]: 0xbfd9db20

Now, my (stupid?) question is:
How can the address of the pointer 'pointer' be the same as array[0] AFTER I have added to it in the loop like this:
Code:

pointer++; // move index by one to array[1], array[2], etc...
It would seem more logical to me that pointer would point to array[9] after the function. If someone could help me solve this little riddle I would appreciate it.

Best,
HMW

lemon09 09-08-2013 02:45 PM

well, this is merely a question of call-by-value or call-by-reference.
actually when you make the call
Code:

fill_arr(pointer, SIZE);
the "pointer" is the actual parameter.

when it comes to
Code:

void fill_arr(int *pointer, int size)
the "pointer" becomes the dummy variable.
For the sake of simplicity let's name the pointer in "fill_arr(pointer, SIZE);" as pointer1
and the pointer in "void fill_arr(int *pointer, int size)" as pointer2. so pointer2 is local to
the function fill_arr. when you make the call to the function the value of pointer1 gets copied into pointer2.
now this pointer2 is manipulated and not the pointer1. but in the main function it is still the pointer1 version.


I hope you got it now.

HMW 09-09-2013 12:49 AM

Quote:

Originally Posted by lemon09 (Post 5024218)
I hope you got it now.

I do! Thanks for pointing out the obvious. Very much appreciate the time you took to explain.

Thanks!
HMW


All times are GMT -5. The time now is 07:16 AM.