Thinking of Memory
There are three ways to modify fragment 1:
Method One: You can add a pointer to the GetMemory function, and then reassign the str pointer in the test function to solve the problem.
Method Two: Because the str pointer in test is pointing to null, the valid address to the space cannot be passed to the GetMemory's formal parameter, so only the STR pointer in the test function points to a non-empty space (no matter how large the size of the space), it can also achieve the solution.
Method Three: Is the following fragment 3
Why add extern "C" to a C + + program that calls the compiled function of the C compiler.
The C + + language supports function overloading, which does not support function overloading. A function is compiled in C + + and the name in the library is different from the C language. Suppose that the prototype of a function is: void foo (int x, int y), the function is _foo in the library after the C compiler is compiled, and the C + + compiler produces names like _foo_int_int. C + + provides an extern "C" of the specified symbol, "C." To resolve the name matching problem.
Writing strcpy functions
char* strcpy (char* strdesc, const char* strsrc)
{
assert ((strdesc!=null) && (strsrc!=null)); Make sure there is space
char* address = Strdesc;
while ((*strdesc++=*strsrc++)!= ' ");
return address;
The function of the return value of the
strcpy: To implement chained expressions. to write constructors for class string, destructors, and assignment functions
Class String
{public
:
string (const char* str = NULL); Normal constructor
String (const string& other); Copy constructor
~string (void); The destructor
string& operator= (const string& other); Assignment function
private:
char* m_data;
string::string (const char* STR/* = NULL */)
{
if (str==null)
{
m_data = new char[1];
*m_data = ' i ';
}
else
{
int length = strlen (str);
m_data = new Char[length+1];
strcpy (M_DATA,STR);
}
string::string (const String &other)
{
int length = strlen (other.m_data);
m_data = new Char[length+1];
strcpy (M_data,other.m_data);
}
String::~string (void)
{
delete[] m_data;
}
string& string::operator= (const string& Other)
{
/Check self assignment
if (this = = &other) return
* this;
Release the original memory resource
delete[] m_data;
Allocates a new memory resource and copies the content
int length = strlen (other.m_data);
m_data = new Char[length+1];
strcpy (m_data,other.m_data);
Returns the reference to this object return
*this;
}
Reference: It's Lin Rui. C + + high quality programming