追加のバッファなしでそれを行う
実際、最も簡単なアプローチは、コピーを避けることです。
#include <string.h>
#include <stdio.h>
int main() {
char a[] = "abcde";
char b[] = "xyz";
printf("%s%s\n", a, b);
return 0;
}
memcpyでそれを行う
memcpyは、n
バイトを からsrc
にコピーしますdest
。文字列のヌル終了バイトを自分で正しくコピーすることを追跡する必要があります。
#include <string.h>
#include <stdio.h>
int main() {
char a[] = "abcde";
char b[] = "xyz";
/* note that both strings add a '\0' termination */
char c[sizeof(a) + sizeof(b) - 1];
/* copy the content of a to c */
memcpy(c, a, sizeof(a));
/* copy the content of b to where a ends (concatenate the strings) */
memcpy(c + sizeof(a) - 1, b, sizeof(b));
/* note that the '\0' termination of the string is necessary to let
* functions like printf know where the string is over
*/
printf(c);
return 0;
}
strcpy と strcat でそれを行う
memcpy を使用する場合、文字列の null 終端を正しく処理するには多くの落とし穴があることに注意してください。文字列のこの手順を簡素化するには、次の手順を実行する必要があります。
これらが実際に文字列であり、ランダムなバイトではない場合は、標準ライブラリの文字列関数に固執する必要があります。これがその方法です。
#include <string.h>
#include <stdio.h>
int main() {
char a[] = "abcde";
char b[] = "xyz";
/* note that both strings add a '\0' termination */
char c[sizeof(a) + sizeof(b) - 1];
/* copy the content of a to c */
strcpy(c, a);
/* copy the content of b to where a ends (concatenate the strings) */
strcat(c, b);
/* note that the '\0' termination of the string is necessary to let
* functions like printf know where the string is over
*/
printf(c);
return 0;
}
弦の大きさを知る上で
バッファのサイズを知ることに関しては、通常は単純にできないことに注意してくださいsizeof(a_string)
。文字配列を関数に渡すと、ポインターに減衰し、この操作は配列の予想されるサイズではなく、ポインターのサイズを返します。
strlen(a_string)
文字列の場合は、null 終端の発生をスキャンし、文字列の長さ (終端を含まない) を返すを発行する必要があります。
ランダム データを含む文字バッファー (または書き込みが必要な空のバッファー) については、このアプローチも機能しません。追加のパラメーターとしてバッファーのサイズを常に渡す必要があります。