Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
void swap1(char **str1_ptr, char **str2_ptr)//here why they have taken pointer to  pointer
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
 
int main()
{
char *str1 = "geeks";
char *str2 = "forgeeks";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}


What I have tried:

I have seen in some blog that i have printed
Posted
Updated 9-Oct-22 23:16pm
v2

In C, values are always passed by value, hence you need the address of the variables in order to actually swap them.
You may see it in the simpler case of integers. Try
#include <stdio.h>

// 'naive' implementation does not work
void swap_int_naive(int a, int b)
{
  int t = a;
  a = b;
  b = t;
}

// using pointers, it works
void swap_int(int *pa, int *pb)
{
  int t = *pa;
  *pa = *pb;
  *pb = t;
}

int main()
{
  int a = 2;
  int b = 4;

  printf("before 'swap_int_naive', a = %d, b = %d\n", a , b);

  swap_int_naive(a,b);

  printf("after 'swap_int_naive', a = %d, b = %d\n", a , b);

  swap_int(&a,&b);

  printf("after 'swap_int', a = %d, b = %d\n", a , b);

  return 0;

}


Then, in order to pass the address of a char * variable, you need a double pointer.
 
Share this answer
 
When you aren't sure about something, start by asking yourself "what would happen if it was different?"

In this case, "what would happen if it was a pointer to a char that was passed?"

What your code is doing is swapping two pointers, so that the variables str1 and str2 "swap strings". But in C, all parameters are passed by value, not reference - which means that a copy of the value is passed to the function. So any changes you make to the parameter variables inside the method you call does not affect the outside world at all - the changes affect only the copy of the value, not the original variable:
void swap1(char **str1_ptr, char **str2_ptr)
    {
    char *temp = *str1_ptr;
    *str1_ptr = *str2_ptr;
    *str2_ptr = temp;
    }
 
void swap2(char *str1_ptr, char *str2_ptr)
    {
    char* temp = str1_ptr;
    str1_ptr = str2_ptr;
    str2_ptr = temp;
    }

int main()
    {
    printf("Hello\n");
    char *str1 = "geeks";
    char *str2 = "forgeeks";
    swap1(&str1, &str2);
    printf("str1 is %s, str2 is %s\n", str1, str2);
    swap2(str1, str2);
    printf("str1 is %s, str2 is %s\n", str1, str2);
    getchar();
    return 0;
    }
The output is the same for both printf calls because the values passed are copies of the pointers and the changes are discarded when the swap2 function exits.

So to change the outside world pointers, you need to pass a pointer to the pointer to the function!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900