Thread: Swapping Addresses by Reference

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    4

    Swapping Addresses by Reference

    Hello:

    I understand C may only change an address via function. However I cannot seem to make that happen. Specific to the code below..."Why doesn't the function SwapAdd modify the addresses in function main?" "What needs to change in order to do so?"

    Thanks!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int SwapAdd (int* ptr1, int* ptr2);
    int main (void) /* begin function main */
    {
     /* Variable Declarations */
     /*-----------------------*/
     int num1 = 5, num2 = 7;
     int *num1Ptr = &num1, *num2Ptr = &num2;
     
     printf ("\n This program swaps pointers to swap addresses \n\n");
     printf ("\n &num1 address is %x\n", &num1);
     printf ("\n num1Ptr address is %x\n", num1Ptr);
     printf ("\n &num2 address is %x\n", &num2);
     printf ("\n num2Ptr address is %x\n", num2Ptr);
     printf ("\n &num1Ptr address is %x\n", &num1Ptr);
     printf ("\n num1 is %d and num2 is %d\n", num1, num2);
     
     SwapAdd (num1Ptr, num2Ptr); /* need to pass pointers */
    
     printf ("\n\n After SwapAdd...\n\n");
     printf ("\n &num1 address is %x\n", &num1);
     printf ("\n num1Ptr address is %x\n", num1Ptr);
     printf ("\n &num2 address is %x\n", &num2);
     printf ("\n num2Ptr address is %x\n", num2Ptr);
     printf ("\n &num1Ptr address is %x\n", &num1Ptr);
     printf ("\n num1 is %d and num2 is %d\n", num1, num2);
     getchar(); /* Wait for character. */
    
     return 0;
    }/* end function main */
    
    /* Function(s) */
    /*--------------*/
    
    int SwapAdd (int* ptr1, int* ptr2)
    {
     int temp;
     temp  = ptr1;
     ptr1 = ptr2;
     ptr2 = temp;
     
     return 0;
    
    }/*end SwapAdd */

  2. #2
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    The address of a pointer is a double pointer, so try coding a different swap() function which will accept double pointers as arguments (and adjust accordingly the code in the function body).
    "Talk is cheap, show me the code" - Linus Torvalds

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Call by Reference: Swapping Array Elements
    By Tripswitch in forum C Programming
    Replies: 8
    Last Post: 07-15-2014, 05:07 AM
  2. Replies: 8
    Last Post: 08-19-2011, 06:53 PM
  3. MAC addresses
    By Thantos in forum Networking/Device Communication
    Replies: 2
    Last Post: 01-20-2004, 02:26 PM
  4. DMA, IO Addresses and IRQ
    By jrahhali in forum Tech Board
    Replies: 1
    Last Post: 08-31-2003, 09:09 AM
  5. dynamic Ip addresses
    By lambs4 in forum Tech Board
    Replies: 5
    Last Post: 01-20-2003, 08:48 AM

Tags for this Thread