sprintf関数の個人的メモ

そろそろプログラミングの季節ですね。

sprintfとは

sprintf, snprintf

sprintfとsnprintfは、引数にchar配列の要素へのポインタstrが追加されたもので、標準出力の代わりにstrへ出力する変種である。snprintfは、さらにstrに書き込んで良い文字数を指定する引数が追加されたものであるが、Cの標準規格に収録されたのはC99からである。
#include
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);

http://ja.wikipedia.org/wiki/Printf

使用例として

こういう文字列を作りたい。

Can you read this? Ican read this!
まちがい

で、例えばこういうコードを書いたとして、

#include<stdio.h>

#define TEXT "can you read this?"

int main( void )
{
	char buf[50] = "I can read this!";
	
	sprintf( buf , "%s %s" , TEXT , buf );
	
	puts( buf );
	
	return 0;
}

これの実行結果(gcc 4.5.3)は

$ ./sprintftest.exe
can you read this? can you read this?

だった。
多分最初の引数に指定した時点で配列がクリアされるのかも。どうなってるんだろう?

正常

こうしてやれば動く

#include<stdio.h>

#define TEXT "can you read this?"

int main( void )
{
	char text[50] = {'\0'};
	char buf[] = "I can read this!";
	
	sprintf( text , "%s %s" , TEXT , buf );
	
	puts( text );
	
	return 0;
}

これの実行結果は、

$ ./sprintftest.exe
can you read this? I can read this!

まとめ

  • sprintf関数で書き込み先の配列と読み込み先の配列に同じ配列を指定することはできない
  • ちゃんと他の配列を作ってやる
  • #defineで定義したやつとmain関数内で宣言した配列の名前が被っている悪いコードなので真似しない。
  • 仮装大会は入賞できなかったくやしい!