zoukankan      html  css  js  c++  java
  • c与c++中输出字符指针和字符串指针的问题

    首先搞清楚在c语言中没有字符串的类型,所以对字符串操作,有两种形式:可以用字符指针,或者字符串数组(这里的指针变量c,系统会为其重新分配内存。

    c程序示例:

      1  #include <stdio.h>
      2
      3 int main()
      4 {
      5   char *a="hello";
      6   char b[]={'l','i','n','u','x'};
      7   char *c=&b[1];
      8
      9    printf("%c ",*a);
     10   printf("%s ",a);
     11   printf("%s ",c);
     12   printf("%s ",b);
     13   printf("%c ",*c);
     14  return 0;
     15 }

    执行效果如下:

    [lm@lmslinux ~]$ ./cp
    h
    hello
    inux
    linux
    i
    4



    其中解引用a时,输出指针指向的第一个字符 “h”,而printf(“%s ”,a)时因为规定了输出字符串的格式,所以不会输出c的地址,而是“hello”这个字符串。 printf("%d ",a)时则输出十进制的c指向的地址。

    c++程序示例:

     1 #include <iostream>
      2 #include <stdio.h>
      3 #include <string.h>
      4 using namespace std;
      5
      6 int main()
      7 {
      8     string s ="string";
      9     string *p=&s;
     10     char * c="hello";
     11     cout<<*c<<endl;
     12     cout<< c<<endl;
     13     cout<<s<<endl;
     14     cout<<*p<<endl;
     15     cout<<p<<endl;
     16     return 0;    
     17 }
    cout输出时是自动判断输出的格式,而且有 string 来表示字符串,*p 解引用输出的是整个字符串,而 p 输出的是字符串的首地址。在cout<<c 时自动判定为输出字符串, * c 解引用c时 输出字符串的第一个字符 “h”。

    执行结果:[lm@lmslinux ~]$ ./test
    h
    hello
    string
    string
    0x7fff97664730

  • 相关阅读:
    用户自定义异常
    触发异常
    第一阶段冲刺终
    第一阶段冲刺七
    第一阶段冲刺六
    第一阶段冲刺五
    第一阶段冲刺四
    Sufficient Statistic (充分统计量)
    DAG-GNN: DAG Structure Learning with Graph Neural Networks
    Masked Gradient-Based Causal Structure Learning
  • 原文地址:https://www.cnblogs.com/sanerer/p/9351189.html
Copyright © 2011-2022 走看看