last-modified: 2019-04-28 (日) 18:36:58 (1834d)[変更箇所]
C++でやるならcharよりもstringを使ったほうが便利。たとえば
int main(int argc,char* argv[]){ string temp[100]; int i; for (i=0;i<argc;i++) temp[i] = argv[i]; cout<<"--- argv"<<endl; for (i=0;i<argc;i++) cout<<i<<" "<<&argv[i]<<" "<<argv[i]<<endl; cout<<"--- temp (copy of argv)"<<endl; for (i=0;i<argc;i++) cout<<i<<" "<<&argv[i]<<" "<<argv[i]<<endl; if (argc>1) temp[1] = find_command(temp[1]); cout<<"--- temp after find_command"<<endl; for (i=0;i<argc;i++) cout<<i<<" "<<&temp[i]<<" "<<temp[i]<<endl; return 0; }
のようなプログラムを考える。find_commandは文字を補完する関数。これを実行すると
> ./findcommand xs aaa --- argv 0 0xbf99bba4 ./findcommand 1 0xbf99bba8 xs 2 0xbf99bbac aaa --- temp (copy of argv) 0 0xbf99bba4 ./findcommand 1 0xbf99bba8 xs 2 0xbf99bbac aaa --- temp after find_command 0 0xbf99b964 ./findcommand 1 0xbf99b968 xstatus 2 0xbf99b96c aaa
のようになる。stringでなくてcharでやるとすべて連続したメモリを使用しているために、temp[1]="xs"が長くなるとその分temp[2]="aaa"が削られて無くなってしまう。その点stringはどのようにメモリに割り当てられているか全然分からないけどそういう煩わしさはなくなる。