-1

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;

}
2
Contributors
1
Reply
14
Views
3 Years
Discussion Span
Last Post by Schol-R-LEA
1

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.