マップに4つの文字列を格納して初めて印刷する次のプログラムがあります。今度は、別の時間を実行して保存された値を取得します。しかし、2回目のリザルトは初めての結果と同じではありません。マップを持つC++プログラムは、前回格納されたものと同じ再割当てをしていません。
#include <map>
using namespace std;
void fun_call(void **,char *);
main(){
void *data=NULL;
char value[100];
int i=0,j=0;
char key[][10]={"disk1","disk2","disk3","disk4"};
cout << "printing all mapped values " << endl ;
data = (void *) malloc(100);
for(j=0;j<2;j++){
for(i=0;i<4;i++){
fun_call(&data,key[i]);
memcpy(value,data,100);
cout << "key ="<<key[i]<<" value is " << value << endl;
}
cout <<"====================="<< endl;
}
}
void fun_call(void **tmp,char name[10])
{
void *tmp_data;
char str[100]="ravindra";
int len =0;
static std::map<std::string,void *> name_data_map;
std::map<std::string,void *>::iterator iter ;
iter=name_data_map.find(name) ;
if (iter == name_data_map.end())
{
len=strlen(str)+strlen(name)+1;
tmp_data = (void *) malloc (len);
strcat(str,name);
memcpy(tmp_data,str,len);
name_data_map[name]=tmp_data;
cout << "Inside the if" << endl ;
}
else
cout << "disk pos "<< iter->first << endl;
cout << "Outside the if" << endl ;
iter=name_data_map.find(name) ;
memcpy(*tmp,iter->second,len);
}
出力:
$ ./a.out printing all mapped values Inside the if Outside the if key =disk1 value is ravindradisk1 Inside the if Outside the if key =disk2 value is ravindradisk2 Inside the if Outside the if key =disk3 value is ravindradisk3 Inside the if Outside the if key =disk4 value is ravindradisk4 ===================== disk pos disk1 Outside the if key =disk1 value is ravindradisk4 disk pos disk2 Outside the if key =disk2 value is ravindradisk4 disk pos disk3 Outside the if key =disk3 value is ravindradisk4 disk pos disk4 Outside the if key =disk4 value is ravindradisk4
2回目の繰り返しのように、すべてのデータを与えている理由を任意のアイデア:中
このメモリコピーとポインタ演算は、すべて非常に難しいです。定義されていない動作を呼び出す可能性は非常に高いですが、気づいていません。 std :: stringを使用して、問題がなくならないか再度確認することを検討してください。 – thiton
合意。私は問題は、あなたが割り当てた後に 'memset'を使って配列を0に初期化しなかったという事実から来ていると思います。 STLコンテナとCスタイルの文字列を混在させるのは悪い習慣です。 –
文字列を扱うときに、なぜvoid *をマップに格納していますか?ここでやったようにタイプセーフな作業ができない理由はありますか?http://stackoverflow.com/questions/10333484/c-program-with-map-explain-the-below-program-how-its-working/10334625#10334625? – stefaanv