I have the following code.According to this the values of pointers p[0] and p[1] remains unchanged since the swap is made to local variables in swap function.Now my doubt is how can I swap the pointers p[0] and p[1] inside the function swap??

#include<stdio.h>
int main()
{

  char *p[2]={"hello","good morning"};
  swap(p[0],p[1]);
  printf("%s %s",p[0],p[1]);
  return 0;
}
   void swap(char *a,char *b)
{
char *t;
  t=a;
  a=b;
  b=t;

}

You will need to you double indirection, i.e., a pointer to a pointer.

#include<stdio.h>

void swap(char **a,char **b);

int main()
{
    char *p[2]={"hello","good morning"};
    swap(&p[0],&p[1]);
    printf("%s %s",p[0],p[1]);
    return 0;
}

void swap(char **a,char **b)
{
    char *t;
    t = *a;
    *a = *b;
    *b = t;
}

Not entirely obvious, but simple enough once you see it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.