#include #include // call by value - the argument does not change value // void assign_00(float val) { val = 99; return; } // call by reference - the argument changes value, // but the memory location doesn't // void assign_01(float* val) { *val = 99; return; } // call by reference for an array: the memory location doesn't change // void assign_02(float* val) { val[2] = 99; return; } // call by reference for an array: the memory location doesn't change // void assign_03(float* val) { val = new float[10]; val[2] = 99; return; } // now we are creating a HUGE memory leak // void assign_04(float** val) { *val = new float[10]; (*val)[2] = 99.0; return; } int main(int argc, char** argv) { // let's demonstrate that val doesn't change // float myval = 27.0; fprintf(stdout, "00: address: <%p> value: <%f>\n", &myval, myval); assign_00(myval); fprintf(stdout, "00: address: <%p> value: <%f>\n\n", &myval, myval); // let's demonstrate that val changes value using call by reference // fprintf(stdout, "01: address: <%p> value: <%f>\n", &myval, myval); assign_01(&myval); fprintf(stdout, "01: address: <%p> value: <%f>\n\n", &myval, myval); // let's use an array, and demonstrate that the pointer doesn't change // value because of scope issues // float aval[10]; aval[2] = 27.0; fprintf(stdout, "02: address: <%p> value: <%f>\n", aval, aval[2]); assign_02(aval); fprintf(stdout, "02: address: <%p> value: <%f>\n\n", aval, aval[2]); // now, let's try to allocate memory in the function: // even though memory is allocated in the function, that // memory is lost when the function exits, because the value // of its argument is not changed. // float* aval2 = new float[5]; aval2[2] = 27.0; fprintf(stdout, "03: address: <%p> value: <%f>\n", aval2, aval2[2]); assign_03(aval2); fprintf(stdout, "03: address: <%p> value: <%f>\n\n", aval2, aval2[2]); // to do this right, we need to use a pointer to a pointer // float* aval3 = new float[10]; aval3[2] = 27.0; fprintf(stdout, "04: address: <%p> value: <%f>\n", aval3, aval3[2]); assign_04(&aval3); fprintf(stdout, "04: address: <%p> value: <%f>\n", aval3, aval3[2]); }