0

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?

4
  • 1
    'cause the first code is using arrays, that can decay to pointers, but they aren't pointers... Commented Sep 12, 2016 at 11:51
  • 4
    Your title is missleading. You don't swap "strings" (aka array contents), but pointers. And C does not enforce using a stack or define the location a variable is stored. Commented Sep 12, 2016 at 11:52
  • 1
    @Gerhard: No, they don't! Commented Sep 12, 2016 at 11:54
  • 3
    Compiler warnings are not for fun! The compiler should warn about the first code. Pay heed to them. First resolve the warnings, then ask a question. Commented Sep 12, 2016 at 11:55

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.