简体   繁体   中英

strings swap in c

    #include<stdio.h>
    void swap(char *, char *);

    int main()
    {
        char *pstr[2] = {"Hello", "IndiaBIX"};
        swap(&pstr[0],&pstr[1]);
        printf("%s\t%s", pstr[0], pstr[1]);
        return 0;
    }
    void swap(char **t1, char **t2)
    {
         char *t;
         t=*t1;
         *t1=*t2;
         *t2=*t;
    }

I don't understand why can't swap the pointer of strings by calling the function like this:

swap(pstr[0],pstr[1]);

I was in a dilemma why I should not use that.Some one please help me.

thanks..

Actually, you have mainly two errors:

  • in the instruction *t2 = *t , *t2 is a string whereas *t is a single character;
  • the declaration of swap is different from its definition.

Also, pstr[0] and pstr[1] can be pointers to read-only strings, so declare them as pointers to const char is considered as a good practice.

In that case, the following code works fine (it swaps just the value of the both pointers, not the strings themselves).

#include <stdio.h>

static void 
swap(const char ** const p, const char ** const q)
{
    const char * const pTmp = *p;
    *p = *q;
    *q = pTmp;
}

int main(void)
{
    const char *p[] = { "Hello", "IndiaBIX" };
    printf("%s - %s\n", p[0], p[1]);
    swap(p, p + 1);
    printf("%s - %s\n", p[0], p[1]);
    return 0;
}

I don't understand why can't swap the pointer of strings by calling the function like this swap(pstr[0],pstr 1 );

Because the swap function expects a pointer to a pointer , not a pointer to a char. It's like that because it changes the actual pointers, not their contents. This C FAQ is relevant.

First, there is mismatch in declaration and definition of the function swap. Look into it.

looks like it's time for you to get acquainted with a debugger. If you're on linux, I can recommend gdb .

Compile your program with debug-info using the -g switch.

Run you program:

gdb -q ./a.out

to set a breakpoint in main :

b main

run program using the r command. Now, step through the code using n and look at the variables using the p command. Good Luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM