Home > Enterprise >  Swapping array problems in c
Swapping array problems in c

Time:01-04

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:

first string is: apple

second string is: hello

final result is: hpple & aello

CodePudding user response:

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("$s", str1) != 1) return 1;

    printf("enter the second string for strswap: ");
    if(scanf("$s", 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);
}

CodePudding user response:

To use a single pointer you need to copy the strings. In your code you only swap the first characters

#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[strlen(str1) 1];
    strcpy(temp, str1);
    strcpy(str1, str2);
    strcpy(str2, temp);
}
  • Related