swapping string and pointers

This is a discussion on swapping string and pointers within the C Programming forums, part of the General Programming Boards category; Code: #include<stdio.h> #include<conio.h> void swap(char *t1,char *t2) { char *t; t=t1; t1=t2; t2=t; } int main() { char *p[2]={"Hello","Jaffna"}; swap(p[0],p[1]); ...

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    4

    Post swapping string and pointers

    Code:
    #include<stdio.h>
    #include<conio.h>
    void swap(char *t1,char *t2)
    {
        char *t;
        t=t1;
        t1=t2;
        t2=t;
     
    }
    int main()
    {
        char *p[2]={"Hello","Jaffna"};
        swap(p[0],p[1]);
        printf("%s\n%s",p[0],p[1]);
        getch();
        
    }
    why swap does not occur?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,589
    The swap does happen. The trouble is, you're only swapping the pointers that are local to the swap function, whereas what you wanted to swap are what the pointers point to. Therefore, you should have char** parameters instead.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    72
    laserlight is right you need to use char ** instead of char *, something like this :

    Code:
    void swap(char **t1,char **t2)
    {
        char *t;
        t=*t1;
        *t1=*t2;
        *t2=t;
    
    }
    int main()
    {
        char *p[2]={"Hello","Jaffna"};
    
        swap(&p[0],&p[1]);
        printf("%s\n%s\n",p[0],p[1]);
        getch();
    
        return 0;
    }
    Regards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. swapping pointers
    By csvraju in forum C Programming
    Replies: 17
    Last Post: 04-01-2009, 03:18 AM
  2. Swapping pointers
    By Mostly Harmless in forum C++ Programming
    Replies: 6
    Last Post: 11-30-2008, 10:07 PM
  3. Swapping Pointers & Arrays
    By bartybasher in forum C++ Programming
    Replies: 6
    Last Post: 10-25-2003, 02:17 PM
  4. Swapping string char with pointers
    By Black-Hearted in forum C++ Programming
    Replies: 4
    Last Post: 06-18-2003, 05:36 AM
  5. Swapping pointers
    By VanJay011379 in forum C++ Programming
    Replies: 3
    Last Post: 07-30-2002, 12:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21