Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swapping array problems in c

I’ve been trying to swap array strings without using string.h or something else. I wrote some code but it only changes the word’s first letter. Where did I make a mistake?

My code is:

#include <stdio.h>
#define SIZE 25

void strswap(char [], char []);

int main(void)
{
    char str1 [SIZE], str2 [SIZE];
    printf("enter the first string for strswap: ");
    scanf("%s", str1);
    printf("enter the second string for strswap: ");
    scanf("%s", str2);
    strswap(str1, str2);
    printf("after strswap, the first string is %s, the second string is %s\n", str1, str2);
    return 0;
}

void strswap(char str1 [], char str2 [])
{
    char temp;
    temp=*str1;
    *str1=*str2;
    *str2=temp;
}

an example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

first string is: apple

second string is: hello

final result is: hpple & aello

>Solution :

str1 and str2 are local to strswap. Any changes you make to those pointers will not be seen at the call site. Also, assigning a single char to temp like you do can not possibly swap the arrays.

If you want to swap the pointer values, provide pointers to the pointers.

Example:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 25

void strswap(char **str1, char **str2) {
    char *temp = *str1;
    *str1 = *str2;
    *str2 = temp;
}

int main(void) {
    char *str1 = malloc(SIZE);
    char *str2 = malloc(SIZE);
    if(!(str1 && str2)) return 1;
    
    printf("enter the first string for strswap: ");
    if(scanf("%24s", str1) != 1) return 1;

    printf("enter the second string for strswap: ");
    if(scanf("%24s", str2) != 1) return 1;
    
    strswap(&str1, &str2); // pointers to the char pointers
    
    printf("after strswap, the first string is %s, the second string is %s\n",
           str1, str2);

    free(str1);
    free(str2);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading