hi everyone:
what the meaning of
int*ptr=new int[0];?
it's compiling, and there isn't a run time error,
so what's the different between that and new int[1] or new int?
thanks alot
hi everyone:
what the meaning of
int*ptr=new int[0];?
it's compiling, and there isn't a run time error,
so what's the different between that and new int[1] or new int?
thanks alot
Simply put, the first is semantically equivalent to setting the array to null, whereas the latter two allocate a single object.
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
thanks for the answer Sebastiani, but i don't think you right because the output of the next code:
the output is an hex address (006148A8 in my case)Code:#include<iostream> using namespace std; int main() { int*ptr=new int[0]; cout<<ptr<<endl; system("pause"); return 0; }
and if were right than the output should be 0(NULL)
Whether you get NULL or an address is implementation-specific, in response to allocating a zero-sized object.
What you cannot do (in either case) is something like
*ptr = value;
ptr[0] = value;
Both of these would be wrong, even if your pointer wasn't NULL.
Likewise, if you did new[0], you must use delete [] to dispose of the object.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Like Salem said, it's implementation defined.
Run it on other compilers and see if it crashes and burns.
It also leaks memory.
Furthermore, trying this on Visual C++...
...fails on the delete statement because we allocated 0 bytes, yet tried to assign 4 bytes we didn't own!Code:int main() { int* p = new int[0]; *p = 10; delete [] p; }
> there isn't a run time error and the output is:976
Good for you - now you understand that "anything" can happen when you make a mess of things.
The safety net underneath the "C++ trapeze artist" is full of holes of varying sizes. Sometimes you get lucky and find a bit of net to save you from your mistakes. Other times, you find a hole and you plummet right into the ground.
Because of this, you need to know the RULES of the language, rather than assuming that every single mistake you can make will be caught by the language. It won't. Sooner or later, a mistake like this would catch up with you.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
all right guys i got it, thank you very much for your time and a special thanks to Salem, i'll follow the RULES from now on :-)