I wrote a code today and I always reported an error. It was originally a left-handed Problem of a string, but I was always bored when I reported an error. Then I went online to answer questions from enthusiastic netizens, and I was very enlightened! Haha, now I want to share it with you!
# Include <iostream>
# Include <cstring>
# Include <malloc. h>
Using namespace std;
Int main ()
{
Char * str = (char *) malloc (20 * sizeof (char); // The first method to open up memory for the pointer
// Char a [20]; // second method for opening up memory for the pointer
// Str =;
// Str = new char [20]; // The third method for opening up memory for the pointer
// Str = "wudemiao"; // The first method for assigning values to pointers
Strcpy (str, "wudemiao"); // assign a second value to the pointer (note the difference)
Cout <strlen (str) <endl;
Cout <str <endl;
Int N = strlen (str );
Int M = 4;
Char ch;
While (M --){
Ch = str [N-1];
For (int I = N-1; I> 0; I --)
{
Str [I] = str [I-1];
}
Str [0] = ch;
}
Cout <str <endl;
// Delete str; // do not drop the third method
// The memory will leak when it is lost.
Return 0;
}
// What needs to be explained is the above description when we open up memory for pointers
// Among the three methods, remember to use delete str; avoid
// Storage leakage. If str = "wudemiao" is used
// The Pointer Points to a String constant. The 20 strings created in the previous sentence are now
// Access failed, which is a serious problem of Memory leakage. Later
// Use the str pointer to modify the constant of the constant it references. The constant must not be
// Modified, so an error occurs. However, use strcpy (str, "wudemiao ");
// Strcpy () generates a copy, which is an array, natural
// Is a variable, so no matter which method you use to open up the memory for the pointer, if you
// If str = "wudemiao" is used, str points to a word.
// Constant, which cannot be changed in C/C ++.
From wudemiao's column