C Pass-By-Reference


Common Error: Passing uninitialized pointer rather than address of existing value

 

    #include <stdio.h>

    /* Code illustrating pass-by-reference */

    /* Function get2Nums:
     * Prompts the user to input two numbers (integers).  
     * Retrieves the numbers from the user, putting them at the addresses
     * POINTED TO by the parameters.
     */
    void get2Nums(int * num1, int * num2);

    void main()  /* broken! */
    {
        int * p1;
        int * p2;
        get2Nums(p1, p2);

        printf ("%d, %d\n", *p1, *p2);
    }

    void main()  /* fixed! */
    {
        int n1;
        int n2;
        get2Nums(&n1, &n2);

        printf ("%d, %d\n", n1, n2);
    }


Alyce Brady, Kalamazoo College