strcat for char[] & char *

I have written code in following manner - part of code is

map<std::string,char *> a;
char y[1000];
sprintf(y,"add this string : %d",val);
char *x = a["M"];

if (x == NULL) //just to check any other value already added at key "M"
{
a["M"] = y;
}
else
{
strcat(x," "); //if something already added add some space & then string
strcat(x,y); //Here it fails.
a["M"] = x;
}



Please let me know what is wrong happennig at failure point.
Unexpectedly, a["M"] will add an entry if doesn't already have value. You need to do a lookup first. So the check is:
1
2
3
4
5
6
7
8
9
10
11
12
std::map<std::string, char*>::iterator p = a.find("M");
if (p != a.end())
{
    // no match found, insert one (using insert)
    a.insert(std::make_pair("M", y);
}
else
{
    // found a match, access the mapped value directly
    strcat(p->second, " ");
    strcat(p->second, y);
}


You do realise that the mapped value is just a char*, if your buffer y[1000] disappears, that char* will be invalid, right?
Last edited on
Well in above case - std::map<std::string, char*>::iterator p = a.find("M") assigns "Bad Pointer" to "p" so p != a.end() becomes false & dosen't executes proper code-
it is due to char * key value.
Any thoughts?
Also strcat(p->second, y) causing application crash.
You do realise that the mapped value is just a char*, if your buffer y[1000] disappears, that char* will be invalid, right?
Do you understand what this means?
Not completely.I am new to C++ 7 playing with char * very first time.Can pls you elaborate more?
In which case, I'm not sure why you opted to use char* in the first place.

You're mapping a string to another string. So the map should be (I'll use a typedef for convenience):
typedef std::map<std::string, std::string> stringmap_type;

Putting it all together, the code should be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
stringmap_type a;

std::ostringstream os;    // this is used to format the string y
os << "add this string : " << val;
std::string y = os.str();

stringmap_type::iterator p = a.find("M");
if (p != a.end())
{
    // no match found, insert one (using insert)
    a.insert(std::make_pair("M", y));
}
else
{
    // found a match, access the mapped value directly
    p->second += std::string(" ") + y;
}
Last edited on
Oh K ,Now I am following this sample but still (p != a.end())
is failing and code in else is getting executed where p->second is not available causing program crash. Can you provide any info. on this?
My mistake. The test should be:
if (p == a.end())
Topic archived. No new replies allowed.