Similarities and differences of character c language pointer variable and the array of characters

1. The character array of a plurality of elements, each element in place of a character, and the character pointer variable is stored in the address (address of the first character string), instead of the character string into a pointer variable.

2. Assignment way. For each element of the array of characters can only be assigned to a character array can not assign the following way.

  • char str[20];
  • str = "ni hao a";

   As for the character pointer variable, you can assign the following ways:

  • char *a;
  • a = "ni hao a";

   Note, however, that is not assigned to a character, but the address of the first element of the string.

3. If you define a character array, allocate memory for it at compile time, it has the exact address. While one character pointer variable, the memory allocated to the pointer variable unit, which may be put in the address of a character variable, i.e., the pointer can point to a variable character data, but if it is not a given address value, it does not point to a definite character data.

4. The character pointer is actually a constant pointer, i.e. char * a fact const char * a. The constant pointer value is not changed, but the point is it can be changed, for example:

#include <stdio.h> 
#include <the iostream> int main () {
     char * B; 
    B = ( char *) " Hello " ;
     // B = "World"; this will be given, because its value can not be change 
    b + = 2 ; // this is true, the hello point b in the second element, i.e. LLO char C [] = " World " ; 
    b = C; // this is also because the point b c first element 
    the printf ( " % S \ n- " , B); 
    System ( " PAUSE " );
     return 0


     ;
}

5. Note that, if the definition of a character pointer variable, and to point to a string, the string pointer variable may be referred to by reference characters with subscripts, for example:

#include<stdio.h>
#include<iostream>

int main() {
    char* b;
    b = (char*)"hello";
    printf("%c\n",b[2]);
    system("pause");
    return 0;
}

Guess you like

Origin www.cnblogs.com/xiximayou/p/12121625.html