Click to See Complete Forum and Search --> : char array vs. char pointer


Al Gruber
02-22-2002, 01:07 PM
Can anybody explain why these things work as they do?

char buff[30], * word1;
cin >>word1; //this bombs
cin >> buff; word1 = buff; //this works, i.e., cout << word1 shows correct
value.

Please don't tell me it works that way because they felt like writing it
that way :)
Thanx, Al

Peter Gotink
02-22-2002, 02:35 PM
word1 is a pointer to char that has not been assiged a value ie no memory
has been allocated. It points into the void, the value is what happens to
be on the stack at that location. This does mean that the code might seem
to work if the word1 happens to be sensible. Of course you'll be
overwriting some other memory location.

If you use the Microsoft C++ and build in debug the compiler will generate
code to 'initialize' these stack variables to all 0xcc characters. That way
an uninitialized value stands out and using an uninitialized pointer will
surely crash your program.

Peter

"Al Gruber" <algruber@home.com> wrote in message
news:3c7688d4$1@10.1.10.29...
>
> Can anybody explain why these things work as they do?
>
> char buff[30], * word1;
> cin >>word1; //this bombs
> cin >> buff; word1 = buff; //this works, i.e., cout << word1 shows correct
> value.
>
> Please don't tell me it works that way because they felt like writing it
> that way :)
> Thanx, Al
>
>