BW> Actually, I think that could overwrite stringvar too, since we're going
BW> to add 2 characters to the end of it, accounting for the null.
RS> No, you will be overwriting the original nul with charvar and
RS> adding a nul for a net increase of 1. Still it won't work
RS> because you are not counting the nul when you call strlen, and
RS> sizeof does count the nul.
yeah, like I just said...?
BW> if(t Works as long as we have the object. If we only have a pointer
RS> sizeof won't be much help. I only mention this because it is
RS> very common to access strings via a pointer, and a newbie will
RS> probably not know the difference.
Now that is a good point. I'm surprised you didn't post a solution
along with your comments about sizeof() so you're saying you can't get
the correct sizeof() for both of these?
char szHappy[]="Happy";
char *Hptr ="Happy";
because sizeof(szHappy) will get us 6, while sizeof(Hptr) only gets us
the size of a char *
The problem was to add a char onto a string which was declared as an
array of char. If we declare the string as char * it would probably
be unwise to try to add anything onto it, but I guess we could create
another pointer to char, copy the old string, append the char, and
assign the new string's address to the original? Do you think this
would work?
char *stringvar="Happy";
char charvar='?';
char *sv=new char[strlen(stringvar)+2];
strcpy(sv, stringvar);
sv[strlen(stringvar)]=charvar;
sv[strlen(stringvar)+1]='\0';
stringvar=&sv[0];
cout << "Are You " << stringvar;
L8r,
bw
... It is bad luck to be superstitious.
--- Blue Wave/DOS v2.20
---------------
* Origin: River Canyon Rd. BBS Chattanooga, Tn (1:362/627)
|