Difference between char pointer and char array

First look at the pointer :

char *p = “helloworld”;

    Here p is a variable whose type is a pointer type and points to a string whose content is "helloworld". If you want to access p[2] , you need to take out the address from p first , which is "helloworld" ” , and then add the offset 2 to get the character 'l' , so the way to access it is to first take the address from p , and then add the offset to the address to get an address , and finally fetch the value from this address . It is divided into three steps :

1. Take the value of p , which is the first address of the string ;

2. Add the offset to the address to get the address of the character to be taken ;

3. Get the value from this address .

Here p is a variable , which itself is stored in an address , and its content is the address of the string "helloworld" . p is separate from the string .

    At the same time , the value of the pointer is determined dynamically , its value must be determined at runtime , and the string can be accessed through this value .

    And if it is an array , then

char p[20] = “helloworld”;

    Here p is the identifier of a string , its type is a character array type , and the array has a size of 20 char types . If you want to access p[2] at this time , it is divided into 2 steps:

1. Directly use the first address of the character array plus the length of the size of 2 char types to get the address of the character to be accessed ;

2. Finally, take out the value from this address . And at this time , the address of p is the first address of the character array , and its content is 'h', a character type .

    So the array and the pointer are different in this place , because the first step of the array value is not to read the address from p to add the offset . At this time, the value of the address of p is ' h' This character , its type is a character type rather than a pointer type . At this time , the address of p is the same as the address of p [ 0] .

    At the same time , the address of each symbol is determined at compile time , so the address of p has been determined here . If you need to access p[2], you can directly use the address plus the offset of 2 to get this value. It does not require the instruction to obtain the first address . In the first case , the instruction also needs to obtain the value in the pointer , and access the string through this value .

    An intuitive view is that the former is two different ,  while the latter is in the same .

    In addition, there is a difference in that in the first case,  p  points to a constant area ,  which cannot be changed ,  that is , p[i] cannot be assigned a value ,  while in the second case , p is a character array ,  It can be changed and can be assigned to p[i] .

  Both of them have the same value of *p, both are h characters!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325598550&siteId=291194637