[C Language] 13-pointer and string

Source: Internet
Author: User

Note: This C language topic is a prelude to iOS development. To enable programmers with object-oriented language development experience to quickly get started with the C language. If you have no programming experience or are not interested in C and iOS development, ignore

String Review

A string is composed of one or more characters, so we can use an array of characters to store the string, but an empty character '\ 0' must be added at the end of the array '.

char s[] = "mj";

The code above defines an array of characters s to store the string "mj". The system will automatically add an empty character '\ 0' at the end '.

The memory distribution is roughly shown in the right figure:

 

From the previous article "12. pointer to one-dimensional array elements", we can see that the pointer is closely related to the array, so we can also use the pointer to operate the string.

1. Use pointers to traverse all characters in a string
1 // define a pointer P 2 char * P; 3 4 // define an array s to store the string 5 char s [] = "mj "; 6 7 // the pointer P points to the string's first character 'M' 8 p = s; // or P = & S [0]; 9 10 for (; * P! = '\ 0'; P ++) {11 printf ("% C \ n", * P); 12}

After 8th rows are executed, the memory distribution is shown in the right figure:

With the previous pointer and array, I believe you can see the code after the first line: before each traversal, determine whether the character currently pointed to by P is a NULL Character \ 0, if it is not a null character, print the current character and execute P ++ to point the pointer P to the next character element.

Final output result:

 

2. Direct pointer to string

We can see from the above that the pointer can indeed point to the string and operate the string. However, the previous practice is: first define a string array to store the string, and then pass the first address of the array to the pointer P, so that P points to the first character of the string.

1. We can also direct a pointer to a string without defining the character array.
1 # include <string. h> 2 3 int main () 4 {5 // define a string and use the pointer s to point to this string 6 char * s = "mj "; 7 8 // use the strlen function to measure the string length 9 int Len = strlen (s); 10 11 printf ("String Length: % d", Len); 12 Return 0; 13}

Note that row 3 points to the string "mj" with the pointer s without creating a character array. Look at row 9th and pass the pointer s into the strlen function, which means that the previously learned string processing function can still be used normally. Output result:

 

2. Let's take a look at the strlen function declaration in string. h.
size_t     strlen(const char *);

The form parameter in the strlen function is the pointer type pointing to the character variable. In "Ten, character and string common processing functions", we can pass in a character array name, this also demonstrates the close relationship between the pointer and the array, and JQ must exist. In fact, when you call the strlen function, you just need to pass an address to it. It calculates the number of characters from this address until it encounters a null character '\ 0, therefore, you can pass in Pointer variables or array names.

The same is true for other string processing functions:

1 char * strcpy (char *, const char *); // string copy function 2 char * strcat (char *, const char *); // String concatenation function 3 int strcmp (const char *, const char *); // string comparison Function

Their parameters are pointer types pointing to character variables, so you can pass in Pointer variables or array names.

Therefore, the printf function can still be used normally:

char *s = "mj";printf("%s", s);

Output result:

 

3. Other methods for pointing a pointer to a string
char *s;s = "mj";

The above pointing method is also correct: first define the pointer variable and then point to the string. This is not allowed if it is a character array. The following method is incorrect:

1 char s[10];2 s = "mj";

The compiler must report the error of row 2nd because S is a constant that represents the first address of the array and cannot be used for value assignment.

Note that the following practices are also incorrect:

1 char *s = "mj";2 3 *s = "like";

Two errors were made in the 3rd line of code:

  • The 3rd line of code is equivalent to saving the string "like" into the memory space pointed to by S. As can be seen from the 1st line of code, s points to the first character 'M' of "mj ', that is to say, s points to a char-type bucket with only one byte. To store "like" in the space of one byte, the memory must overflow.
  • The Code in line 1st shows that the pointer s points to the String constant "mj "! Therefore, you cannot use pointers to modify the string content! Even if it is * s = 'A' and "It seems correct", it is also wrong, because s points to a constant string and cannot modify its internal characters.

 

3. Notes on Pointer processing strings

Now you want to change the first character 'l' of the string "LMJ" to 'l', there are multiple solutions

1. solution 1
1 // define a string variable "LMJ" 2 char a [] = "LMJ "; 3 4 // change the first character of the string to 'L' 5 * A = 'l'; 6 7 printf ("% s", );

The program runs normally and the output result is:

 

2. Someone should be able to immediately think of the second solution.
1 char *p2 = "lmj";2 *p2 = 'L';3 4 printf("%s", p2);

It seems feasible, but this is the error code and the error is in line 2nd. First, let's take a look at row 1st. the pointer variable P2 points to a String constant. Because it is a constant, its internal characters cannot be modified.

Someone may be confused. Here the 1st line code char * P2 =
"LMJ"; with the 2nd line code in the first solution char a [] =
"LMJ"; isn't it the same? This is different.

  • Char A [] =
    "LMJ"; defines a string variable!
  • Char * P2 =
    "LMJ"; defines a String constant! Strictly speaking, it should be written as const
    Char * P2 =
    "LMJ";, with a constant Modifier

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.