[Tutor] How to do call by reference (or equiv.) in Py?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Nov 22 17:05:02 2002


> Here's an analogous situation in C:
>
> /***/
> #include <stdio.h>
> int* sum(int *x, int *y) {
>     int *z = malloc(sizeof(int));
>     *z = *x + *y;
>     return z;
> }
>
>
> int main() {
>     int *x, *y, *sum;
>     x = malloc(sizeof(int));
>     *x = 42;
>     y = x;
>     sum = add(x, y);
>     printf("%d + %d = %d", *x, *y, *sum);
>     return 0;
> }
> /***/



... except that this C code doesn't compile.  Doh.  Here's the corrected
code:


/******/
#include <stdio.h>

int* add(int *x, int *y) {
    int *z = (int*) malloc(sizeof(int));
    *z = *x + *y;
    return z;
}


int main() {
    int *x, *y, *sum;
    x = (int*) malloc(sizeof(int));
    *x = 42;
    y = x;
    sum = add(x, y);
    printf("%d + %d = %d\n", *x, *y, *sum);
    return 0;
}
/******/


Sorry about that!