The format char* ptr = "string here"; is deprecated from C++. Use the option given by Moschops. In fact strings are arrays in C, but they are ended with a 0x00 character called string terminator.
1 2
|
// for example a string like
char cp2[] = "jjjjjj";
|
Will generate :
'j' <--- Cp2 points to here
'j'
'j'
'j'
'j'
0x00
The strcpy function will copy the second string to the first string by indexing this copy using the pointer to the start of the array . Cp2 and Cp1 are both pointers to the first item of the array.
You can see that both have different sizes and strcpy will not be able to copy the block memories because of this.
Strcpy it self is not a recommended function as there is a safer one strncpy that asks for the size of the buffer that is copied.
You have 3 options:
1- declare cp2 as a large buffer
1 2 3 4 5
|
char _buffer_[10];
//initated it
memset(_buffer_,0,10);// already has a terminator
//copy the string
strncpy(_buffer_,cp2,strlen(cp2));
|
2- Declare buffer dynamically
1 2 3 4 5 6
|
char* _buffer_ = new char[strlen(cp2)+1];
strncpy(_buffer_,cp2,strlen(cp2));
_buffer_[strlen(cp2)+1] = 0x00;
// use _buffer here
// deallocate it
delete[] buffer;
|
3-There is a string class on c++ , actually std::string
to use it:
1 2
|
#include <string>
using namespace std;
|
Note that string does not have a 0x00 terminator ( the char strings are also called NULL terminated strings ) but has lots of facilities that you make your life easier. Sometimes, it is useful to use C Style strings, especially when you are dealing with ascii characters or binary files.