1. 程式人生 > >c與c++中輸出字符指針和字符串指針的問題

c與c++中輸出字符指針和字符串指針的問題

cout 指針 inux 問題 執行 格式 一個 輸出 []

首先搞清楚在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\n",*a);
10 printf("%s\n",a);
11 printf("%s\n",c);
12 printf("%s\n",b);
13 printf("%c\n",*c);
14 return 0;
15 }

執行效果如下:

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



其中解引用a時,輸出指針指向的第一個字符 “h”,而printf(“%s\n”,a)時因為規定了輸出字符串的格式,所以不會輸出c的地址,而是“hello”這個字符串。 printf("%d\n",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

c與c++中輸出字符指針和字符串指針的問題