<sh********@gmail.comwrote in message
news:11*********************@q16g2000cwq.googlegro ups.com...
Hi,
I am creating a pointer to char:
char * lDirName = new char;
I am trying to set values character by character.
lDirName[0]= 'c';
lDirName[1]= ':';
lDirName[2]= '\\';
The problem is that, the memory address that "lDirName " is pointing to
has some junk value in it. so instead of "lDirName" taking value as
"c:\" it takes value as "c:\1" or anything that is there in the memory.
I can't use static array because I don't know how long "lDirName "
going to be.
how to overcome this problem?
If you can't use std::string for some reason, then you could try this:
get the length of the original string
new[] an array of char that's two larger (one for the new character, and
one for the NULL-terminator)
copy the old to the new
append the new character and a NULL-terminator
delete[] the old string
set the original pointer to point to the new string
(You should also new your original string with [1], and initialize it with
"", so that it has a NULL-terminator already.)
Or, assuming that this is in some kind of loop, you could use two loops, one
whose sole job is to determine the length of the string that you'll need,
and then another to actually fill it (after allocating enough space for the
string, plus one for the NULL-terminator).
(There may also be other ways to accomplish what you want, but you haven't
shown us how you're getting those individual characters, so it would be
difficult to guess on any improvements in that area.)
In my opinion, it should now be obvious, from the work required above if
nothing else, that using std::string is the better choice.
-Howard