cout and char*

i am really confused and do not understand why it was working yesterday and i woke up today and it is doing something weird

1
2
3
4
5
6
7
8
9
10
void main(void){
     char* lpBuffer = new char[20];

     strcpy(lpBuffer, "$P01A?S"); // This is actually a RS232 ReadSerial return 
                             // string but for this purpose strcpy() is
                             // same basic function
     cout << lpBuffer << endl;
     cout << *lpBuffer << endl;
     cout << lpBuffer[0] << lpBuffer[1] << lpBuffer[2] << endl;
}


output:
Program F-[down arrow]p[paragraph]>0
$
$P0

how come when i try and print the char* as a whole, cout << lpBuffer << endl, it looks as though it jumps to some random memory space. and when i call for individual character locations it appears to know where to look. am i missing something totally obvious here?

thanks

[EDIT]
Solved
it was a mistake on my part in which i was receiving a string, why i did not get this error yesterday i do not know.

basically the readserial function does not put a string terminator on the char* for some reason. so when i was printing i was printing random stuff. the reason it looked like 100% random stuff was because one of the symbols i send is (char)13 so it was carriage returing and overwriting the first values.
Last edited on
The code you posted will not generate the output you gave. You must be running different code.


What's likely is that you were attempting to print lpBuffer before you did the strcpy to fill its contents. In which case whatever random, uninitialized garbage memory was in the buffer will get printed.

But again... the code you posted does not have that problem.
Last edited on
no this is the code i am running and it is generating that output.

and i agree it shouldn't an di understand if no one can answer because i am totally lost in the matter here.
no this is the code i am running and it is generating that output.


You must be mistaken.

Try cleaning/rebuilding. Maybe you're running an outdated exe. Or maybe your source file hasn't been saved. Or maybe you are modifying a different file than the one you are compiling.
Topic archived. No new replies allowed.