Thread: swapping string and pointers

  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
    28,412
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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, 11: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