実現したいこと
題の通りスワップをどのように実装するのがいいのかお聞きしたいです。皆様ならばどのように実装いたしますか?
私は以下のように考えました。
MAX_LENは決められたものとします。またコンパイル方法はコードの下のコメントのようにオプションをつけます。
現在の方法
C
1#include <stdio.h> 2 3#define MAX_LEN 5 4 5void copy(char *s1, char *s2, int n) 6{ 7 while (n--) { 8 if (!(*(s1++) = *(s2++))) 9 break; 10 } 11 while (n--) 12 *s1++ = '\0'; 13} 14 15void swap(char *s1, char *s2) 16{ 17 char tmp[MAX_LEN+1]; 18 copy(tmp, s1, MAX_LEN+1); 19 copy(s1, s2, MAX_LEN+1); 20 copy(s2, tmp, MAX_LEN+1); 21} 22 23int main(void) 24{ 25 char a[] = "Hello"; 26 char b[] = "World"; 27 printf("%s %s\n", a, b); 28 swap(a, b); 29 printf("%s %s\n", a, b); 30 return 0; 31} 32/* 実行 */ 33/* $ gcc -O -Wall -pedantic -ansi -o t test.c */ 34/* $ ./t */ 35/* Hello World 36 World Hello */
実行環境
gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。