Pass by address

I'm confused for the two functions here b/c although both pass by address so implies uses a pointer in the function declaration and in the call in main, the first function needs to use the address-of operator BUT not for the second which uses an array. Why won't an & be needed in front of PrintArray(&list,size)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void foo(int *pValue)
{
    *pValue = 6;
}
 
int main()
{
    int nValue = 5;
 
    cout << "nValue = " << nValue << endl;
    foo(&nValue);
    cout << "nValue = " << nValue << endl;
    return 0;
}


VS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void PrintArray(int *pnArray, int nLength)
{
    // if user passed in a null pointer for pnArray, bail out early!
    if (!pnArray)
        return;
 
    for (int iii=0; iii < nLength; iii++)
        cout << pnArray[iii] << endl;
}

int main()
{
 int list[5] = {12,87,99,23,8};
	
 int size = 5;
	
 PrintArray(list, size);
 
 return 0;  
}
Last edited on
Array names are equivalent to pointers to the first element in some contexts. Using one as an argument to a function is one of those contexts.
An array name without any brackets is a shortcut -- it gives you a pointer to the first element. (technically an array name is not really a pointer, but can be cast to a pointer -- but nevermind that, that detail will probably just confuse you.)

Example:

1
2
3
4
5
6
7
int array[5];

// this...
int* p = array;

// is the same as this...
int* p = &array[0];


You do not simply use &array because that would be a different type. Remember in this case array is an array, not an int, so &array would be a pointer to an array, not a pointer to an int.

Since your PrintArray function takes a pointer to an int, passing it &list wouldn't work. But passing it &list[0] would... since list[0] is an int, &list[0] would be a pointer to that int.
Last edited on
The reason for this apparent oddity with passing arrays is historical.

The C programming language's predicessor, the B programming language, implemented arrays (called vectors in that language) as a pointer to a block of memory. So when you passed an array around, you know that you were only passing a pointer.

This was changed in C. In C (and C++), when you declare an array, you get a block of memory, not a pointer to a block of memory as you did in B. But the syntax for functions accepting arrays was not changed. That's why there's a mismatch between the definition of an array and the way it's passed to functions. (This was changed somewhat in C99.)

Unfortunately, it's just one of those inconsistencies you have to accept about C and C++.
Last edited on
Indeed, C-style arrays carry several scars of backwards compatibility with B. Here's a link to DMR's history of C for some extra pointers: http://cm.bell-labs.com/cm/cs/who/dmr/chist.html
Topic archived. No new replies allowed.