21.6.  Arrays, Functions, and Return Values

[ fromfile: memoryaccess.xml id: arraysandfunctions ]

Example 21.5. src/arrays/returningpointers.cpp


#include <assert.h>

int paramSize;

void bar(int* integers) {
    integers[2]=3;                      1
}

int* foo(int arrayparameter[]) {
    using namespace std;
    paramSize = sizeof(arrayparameter);
    bar(arrayparameter);                2
    return arrayparameter;              3
}
    
int main(int argc, char** argv) {
    int intarray2[40] = {9,9,9,9,9,9,9,2,1};
    char chararray[20] = "Hello World"; 4
    int intarray1[20];                  5
    int* retval;                        6

//  intarray1 = foo(intarray2);         7

    retval = foo(intarray2);
    assert (retval[2] == 3);
    assert (retval[2] = intarray2[2]);
    assert (retval == intarray2);
    int refSize = getSize(intarray2);
    assert(refSize == paramSize);
    return 0;
}

1

Change the third element in the incoming array.

2

Pass an array by pointer to a function.

3

Return an array as a pointer from a function.

4

Special syntax for initializing char array.

5

Uninitialized memory.

6

Uninitialized pointer.

7

Error, intarray1 is like a char* const, it cannot be assigned to.