0
#include <stdio.h> #include <string.h> int main() { char str1[100]; char str2[100]; printf("(1) input str1: "); scanf_s("%s", str1, sizeof(str1)); printf(" input str2: "); scanf_s("%s", str2, sizeof(str2)); strcpy_s(str2,100,str1); printf("(2) exchange str1=%s str2=%s\n", str1, str2); printf("len1=%d len2=%d\n", strlen(str1), strlen(str2)); 

i would change str1 to str2 each other.

At first i'd written 'strcpy_2(str2,str1)', But VS said i need more parameter, so i wrote 'strcpy_s(str2,100,str1).

Although error isn't founded, the result is wrong. str1 and str2 has same value about str1.

What is my problem? Thank you.

9
  • Are you allowed to use a temporary string? It might be worth the speed of memcpy just to do that. Commented Mar 24, 2021 at 4:48
  • 1
    You're only copying once. How could that possibly interchange the strings? Commented Mar 24, 2021 at 4:49
  • 2
    Copy str2 to a temporary string, copy str1 to str2, then copy the temporary string to str1. That's the usual method for any kind of swap. Commented Mar 24, 2021 at 4:50
  • Thank you Barmar. I made a big mistake. Have a good day Commented Mar 24, 2021 at 4:54
  • 1
    You could also use an XOR loop over the strings. So you wouldn't need a temp string. Commented Mar 24, 2021 at 6:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.