cppaddict <he***@hello.co m> wrote in message news:<k3******* *************** **********@4ax. com>...
I thought that:
char x[2];
made x into a pointer-to-char.
No -- this defines x as an array of char.
But how come the following code won't compile:
int main() {
char pbuf[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
pbuf = new char[2]; //Lvalue Required ERROR
Because an array isn't a (modifiable) lvalue.
[ ... ]
Why won't the first example work?
Your code is ill-formed because your understanding about x was
incorrect.
As you've defined it above, x is an array. If you were to pass x as a
parameter to a function, then what would be passed would be a pointer
to the beginning of the array, but here you're not passing it as a
parameter. As it stands right now, you're trying to assign to x which
is an array, and assigning to an array simply isn't allowed.
Note that as a parameter, what you get is a pointer even if you use
array-style notation in the function declaration/definition. For
example:
void f(char x[2]) {
// This is well-formed code. The '2' above is entirely ignored
// so we can assign a pointer to a larger array, such as:
x = new char[20];
}
You can argue (and I'd agree) that this is usually a bad idea, but the
compiler won't do a thing to stop it. If you're feeling particularly
ornery, you can even do something like:
void f(char x[2]);
void f(char *x) { }
and get away with it -- at least with the compiler. Of course, if any
of your co-workers find out, it's your problem, not mine! :-)
--
Later,
Jerry.
The universe is a figment of its own imagination.