【发布时间】:2012-05-07 04:32:56
【问题描述】:
在下面的程序中,tmp_data 首先打印为:“Ravindra Kumar”。但是在复制到地图后,它变成了“RRRRRRRRRRR”。当我们下次打印时,它仍然在打印“Ravindra Kumar” - 如何。应该是打印RRRRRRRR吧?
#include <iostream>
#include <cstring>
#include <string>
#include <map>
using namespace std;
void fun_call( );
main(){
cout << "printing all data " << endl ;
fun_call();
fun_call();
}
void fun_call()
{
// static void *tmp_data;
void *tmp_data;
char *str="Ravindra Kumar";
char *str1="RRRRRRRRRRRRRRRRRRRRR";
char name[]="Ravi";
char value[100];
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())
{
tmp_data = (void *) malloc ( strlen(str)+1 );
memcpy(tmp_data,str,strlen(str)+1);
name_data_map[name]=tmp_data;
cout << "Inside the if" << endl ;
}
cout << "Outside the if" << endl ;
iter=name_data_map.find(name) ;
memcpy(value,iter->second,strlen(str)+1);
cout << "value is " << value << endl ;
tmp_data=(void *)malloc(100000);
memcpy(tmp_data,str1,strlen(str1)+1);
}
输出:
$ ./a.out
printing all data
Inside the if
Outside the if
value is Ravindra Kumar
Outside the if
value is Ravindra Kumar
【问题讨论】:
-
主函数的损坏签名表明您正在使用不兼容的编译器。是哪个?
-
添加了
c标签,因为这实际上是一个 C 问题而不是 C++。 -
这是一个 C 问题吗?
using、namespace、cout、map、string、::,滥用<和>都不是C! -
@pmg,检查OP的实际问题。它与
void*指针有关,OPmalloced 两次,memcpyd 将两个char*文本字符串的内容放入其中。您可以将std::map替换为数组,将cout替换为printf并删除所有其余的 C++ 内容,而不会影响主要问题。
标签: c++ dictionary iterator