C
cppaddict
I thought that:
char x[2];
made x into a pointer-to-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
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;
return 0;
}
In contrast, the following code compiles and runs as expected:
int main() {
char *pbuf;
pbuf = new char[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;
pbuf = new char[2];
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;
return 0;
}
Why won't the first example work?
Thanks,
cpp
char x[2];
made x into a pointer-to-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
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;
return 0;
}
In contrast, the following code compiles and runs as expected:
int main() {
char *pbuf;
pbuf = new char[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;
pbuf = new char[2];
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;
return 0;
}
Why won't the first example work?
Thanks,
cpp