[過去ログ] 【初心者歓迎】C/C++室 Ver.102【環境依存OK】 (1002レス)
前次1-
抽出解除 必死チェッカー(本家) (べ) 自ID レス栞 あぼーん

このスレッドは過去ログ倉庫に格納されています。
次スレ検索 歴削→次スレ 栞削→次スレ 過去ログメニュー
501
(1): デフォルトの名無しさん [sage] 2018/04/09(月) 18:49:30 ID:m9zaOBXx(1/4) AAS
test2の形だと上手く動作しないのですが何故でしょうか
環境はvc6とstlport521です

void test1(const char* cstr, ...) {
char buf[1024];
va_list args;
va_start(args, cstr);
vsprintf(buf, cstr, args);
va_end(args);
printf(buf);
}
void test2(std::string str, ...) {
const char* cstr = str.c_str();
char buf[1024];
va_list args;
va_start(args, cstr);
vsprintf(buf, cstr, args);
va_end(args);
printf(buf);
}
void main() {
test1("hello1 %d\n", 123);
test2("hello2 %d\n", 123);
}
//結果
//hello1 123
//hello2 1819043176
503: デフォルトの名無しさん [sage] 2018/04/09(月) 19:06:25 ID:m9zaOBXx(2/4) AAS
引数を参照とポインタでも試してみましたが結果は変わらなかったです

void test3(std::string& str, ...) {
const char* cstr = str.c_str();
・・・
void test4(std::string* str, ...) {
const char* cstr = str->c_str();
・・・
void main() {
・・・
std::string str3("hello3 %d\n");
test3(str3, 123);
std::string str4("hello4 %d\n");
test4(&str4, 123);
}
//結果
//hello1 123
//hello2 1819043176
//hello3 1819043176
//hello4 1819043176
506: デフォルトの名無しさん [sage] 2018/04/09(月) 19:22:49 ID:m9zaOBXx(3/4) AAS
ああなんとなく意味が分かってきました
va_startはマクロであってcstrの部分は引数の変数名が指定されなければならないということですかね
507
(1): デフォルトの名無しさん [sage] 2018/04/09(月) 19:41:37 ID:m9zaOBXx(4/4) AAS
こういうコードにすると期待した動作をするようになりました
ありがとうございました

void test5(std::string str, ...) {
char buf[1024];
va_list args;
va_start(args, str);
vsprintf(buf, str.c_str(), args);
va_end(args);
printf(buf);
}
void main() {
・・・
test5("hello5 %d\n", 123);
}
//結果
//hello1 123
//hello2 1819043176
//hello3 1819043176
//hello4 1819043176
//hello5 123
前次1-
スレ情報 赤レス抽出 画像レス抽出 歴の未読スレ AAサムネイル

ぬこの手 ぬこTOP 0.041s