美文网首页
字符类型的指针

字符类型的指针

作者: EdisonDong | 来源:发表于2016-12-04 10:44 被阅读0次

    例子

    #include <stdio.h>
    
    int test_char(){
      char name[] = "Tom";
      printf("%s\n",name);
      printf("%s\n",*name);
    }
    
    int test_char_pointer(){
      char *name = "Tom";
      printf("%d",name);
      printf("%d",*name);
      printf("%d",&name);
      printf("%s",name);
      printf("%d",*name);
    }
    
    void split_line(){
      int count = 20;
      for(int i = 0;i < count;i++){
        printf("%c",'-');
      }
      printf("\n");
    }
    
    int main(){
      test_char();
      split_line();
      test_char_pointer();  
    }
    

    在预测结果前,先弄清几个概念

    • 什么是指针
      指针是计算器在内存中开辟的一段内存空间,空间存放的是它所指向的变量的地址,所以当然指针也是有它自己的地址的:
      比如char *name = "Jack"这个代码片段,字符串"Jack"在内存中的地址是11399,指针变量name存放的就是11399这个地址,当打印name的地址(注意是地址),却是20118
    • 如何声明指针变量
      与生命其他变量类似,但需要在变量前加上*号:
      type *variable;
    char *name = "Jack";//name指向字符串Jack的第一个字符地址
    char *name;//定义一个字符类型的指针
    char other_name[20] = {'J','a','c','k'};
    name = &other_name;//name指针指向变量other_name的地址
    
    • 如何取一个变量的地址
      使用&符号获取一个变量的地址,这个变量可以是一般类型的变量,也可以是指针类型的变量:
    char *p;
    char name[] = "Jack";
    p = &name;
    
    • 如何取指针指向变量的值
    char *p = "Jack";
    char p_value = *p;
    

    运行结果

    如果理解以上的概念,不难计算出以下答案:

    #include <stdio.h>
    
    int test_char(){
      char name[] = "Tom";
      printf("%s\n",name);//Tom
      printf("%s\n",*name);//出错 name不是一个指针 不能使用取值符号*
    }
    
    int test_char_pointer(){
      char *name = "Tom";
      printf("%d",name);//12233
      printf("%d",*name);//84
      printf("%d",&name);//238677
      printf("%s",name);//Tom
      printf("%d",*name);//出错
    }
    
    void split_line(){
      int count = 20;
      for(int i = 0;i < count;i++){
        printf("%c",'-');
      }
      printf("\n");
    }
    
    int main(){
      test_char();
      split_line();
      test_char_pointer();  
    }
    

    相关文章

      网友评论

          本文标题:字符类型的指针

          本文链接:https://www.haomeiwen.com/subject/zcgcmttx.html