値を引数にセットして返す方法
引数で渡された参照に対して、文字列をセットして返す方法が自分の中でシックリこなかったので、簡単にまとめ。一つは文字列の参照を渡す方法で、もう一つはポインタのポインタを渡す方法。見た目的にもコード的にも参照で渡してセットする方が簡単かな。
サンプルコード
#include <iostream> using namespace std; void hoge1 (char* &buf) { buf = const_cast<char*>("hoge1"); } void hoge2(char** buf) { *buf = const_cast<char*>("hoge2"); } int main() { { char* buf; hoge1(buf); cout << buf << endl; } { char** buf; hoge2(buf); cout << *buf << endl; } return 0; }
実行結果
hoge1 hoge2