Harsha Vardhan Harsha Vardhan - 2 months ago 10
C Question

swapping two strings stored in character arrays C

1.C code for swapping two strings stored in character arrays.

#include<stdio.h>

/* Swaps strings by swapping pointers */
void swap1(char **str1_ptr, char **str2_ptr)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}

int main()
{
char str1[10] = "geeks";
char str2[10] = "forgeeks";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}


2.C code for swapping two strings stored in read only memory.

#include<stdio.h>

/* Swaps strings by swapping pointers */
void swap1(char **str1_ptr, char **str2_ptr)
{
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;
}


These two are codes for swapping two strings (one string stored in stack,other in read only memory).
Will they work the same?
It is said that first code will not work properly.
If so, Why?

Answer

The first example will not work because you are not really passing pointers to pointers in the call to the swap1 function, you are passing pointers to arrays.

The type of the expression &str1 is not char**, it is char (*)[10]. It is a very big difference, and that will lead to all kind of problems when attempting to dereference those pointers and swap them.