Still i don't understand what is the meaning of :
char * ch=new char[3];
Is it that: i can store one string which length is 3 characters
or: i can store 3 strings that their sizes are not important.
Which is right?
Thanks.
Still i don't understand what is the meaning of :
char * ch=new char[3];
Is it that: i can store one string which length is 3 characters
or: i can store 3 strings that their sizes are not important.
Which is right?
Thanks.
> Is it that: i can store one string which length is 3 characters
Actually, it's two chars and a \0
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.
Thnaks for answer
But why does this code work?
There is no error
Code:#include <iostream> using namespace std; int main() { char * ch=new char[3]; ch="iaisiaiaisiiai"; cout<<ch; return 0; } ///:~
> But why does this code work?
Well it only "works" because you don't call
delete [ ] ch;
Also, "works" is generally assumed to only mean "produces expected output and doesn't crash". This is somewhat different from "bug free".
Your assignment does not copy the string to the allocated memory, it just assigns a new pointer (and loses the pointer new returned in the process).
If you allocated enough space, then you would do this
strcpy ( ch, "iaisiaiaisiiai" );
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.
thanks salem.
Note that even if you don't allocate enough space, even the use of strcpy might appear to work. However, this is what is called undefined behavior and means that your program might crash or might appear to work, and you don't really know which one it will be at any time.