pass by address without the &

Apr 10, 2016 at 6:18pm
Am studying passing by address: fx foo(&value) uses the argument address(&) to pass to function parameters. In the second example where printArray(array, 6) no address & used--its as if the array is passed without an & operator for address. Why is this the case?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>

void foo(int *ptr)
	{
	    *ptr = 6;
	}

void printArray(int *array, int length)
	    {
	        for (int index=0; index < length; ++index)
	            std::cout << array[index] << ' ';
	    }

int main()
	{
	    int value = 5;

	    std::cout << "value = " << value << '\n';
	    foo(&value);
	    std::cout << "value = " << value << '\n';
	    int array[6] = { 6, 5, 4, 3, 2, 1 };
	    printArray(array, 6);



	    return 0;
	}

Last edited on Apr 10, 2016 at 6:20pm
Apr 10, 2016 at 6:19pm
When you pass an array, what actually gets passed is a pointer to the first element in the array. Typically we say the array parameter decays to a pointer, but what we call it doesn't matter. That's what happens. It's how C and C++ works.
Last edited on Apr 10, 2016 at 6:27pm
Apr 10, 2016 at 7:16pm
Yes, all of what you said is true, thx. Narrow the question: how is this argument passed by address? Where is address info? Sorry to fuss over such an banal question.
Last edited on Apr 10, 2016 at 7:19pm
Apr 10, 2016 at 7:33pm
Maybe it would look more like an address if you replaced this
 
    printArray(array, 6);
by this:
 
    printArray(&array[0], 6);
Apr 10, 2016 at 9:02pm
Yes
Thx
That was the missing piece.
Topic archived. No new replies allowed.