-
I'm confused!
Hey guys!
I hope you can help me sort one thing out. Why i cannot do this?
Code:
char* ptr = new char[40];
ptr = "First string";
strcpy(ptr, "New string");
However, if i would write this
Code:
char* ptr = new char[40];
strcpy(ptr, "First string");
strcpy(ptr, "New string");
then everything would work out and contents of ptr would change to the new string. In other words, how does function strcpy change from normal assignment. Thank you.
-
In the first case, you are assigning the address of "First string" into ptr and then you are trying to overwrite it with strcpy() which is a no-no. In the other case, strcpy() uses the pointer as an array and does not change the address contained in the pointer. You could prevent this by having a const pointer to a char like this:
Code:
char const* ptr = new char[40];
ptr = "First string"; // compile-error : cannot change memory address, declared char const*
strcpy(ptr, "New string");
Besides, using new[] with a constant size isn't much useful at all. Just to make sure you know.
-
Quote:
Code:
char const* ptr = new char[40];
ptr = "First string"; // compile-error : cannot change memory address, declared char const*
Actually, no. char const* is the same as const char* so you will get a compile error on the strcpy line. I think you meant:
Code:
char *const ptr = new char[40];
ptr = "First string";//error
strcpy(ptr,"New string"); //ok
-
So, to make sure i got it - using strcpy is like overwriting existing address with new value. And using operator = is just changing the address to a new value.
-
Character arrays tend to be rather confusing unless you do simple stuff with them or have a good understanding of pointers, arrays and constants. If you just want to work with text, you may be better off using C++ style "string" objects, which are safe and easy to handle (even if you do have a good understanding of character arrays): http://www.cprogramming.com/tutorial/string.html
-
This is a good read on the subject too: http://pw1.netcom.com/~tjensen/ptr/pointers.htm
It says C but applies to C++ if you're using char arrays, in case you were wondering.