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.

  • Are you allowed to use a temporary string? It might be worth the speed of `memcpy` just to do that. – Neil Mar 24 '21 at 04:48
  • 1
    You're only copying once. How could that possibly interchange the strings? – Barmar Mar 24 '21 at 04: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. – Barmar Mar 24 '21 at 04:50
  • Thank you Barmar. I made a big mistake. Have a good day – Kim ByeongHwa Mar 24 '21 at 04:54
  • 1
    You could also use an XOR loop over the strings. So you wouldn't need a temp string. – paladin Mar 24 '21 at 06:11
  • @Neil Why do you think is `memcpy()` faster than `strcpy()`? – the busybee Mar 24 '21 at 08:32
  • @thebusybee see this discussion on [memcpy _vs_ strcpy](https://stackoverflow.com/questions/24966693/is-memcpy-usually-faster-than-strcpy). Xor loop is `O(1)` space, but I imagine testing for equality would be a major slowdown. – Neil Mar 24 '21 at 19:11
  • @Neil As I thought, this is **not a general** rule, as the accepted answer shows. It depends heavily on the target system and the implementation of these library functions. -- Anyway, replacing `strcpy()` by `memcpy()` in this case is bad: the data to copy are strings, and the may-be-or-not advantage of some microseconds in the context of human input is not worth this loss of source code clarity. There is little worse than premature optimization. I would only do this if the requested performance cannot reached otherwise. – the busybee Mar 24 '21 at 20:27
  • Agreed, there is so little data here that clarity of intent should be preferred. @KimByeongHwa if you get it working, I think answering your own question is appropriate, explaining your thought process. That way people with the same problem can search for it. – Neil Mar 24 '21 at 23:41

0 Answers0