char *和int *有什麼區別?char *和int *的區別是什麼?C++ char * vs int *
例如,當我跑這樣的代碼:
#include<iostream>
using namespace std;
int main(){
int a[3] = {10, 20, 30};
int *ptr2a = &a[0];
int i;
char line[] = "Hello";
char *ptr2line = &line[0];
for(i=0; i<3; i++){
cout<<"Value of a["<<i<<"] is: "<<a[i]<<" same as "<<*(ptr2a+i);
cout<<" Address is: "<<ptr2a+i<<" , same as "<<&a[i]<<endl;
}
for(i=0; i<strlen(line); i++){
cout<<"Value of line["<<i<<"] is: "<<line[i]<<" same as "<<*(ptr2line+i);
cout<<" Address is: "<<ptr2line+i<<" , same as "<<&line[i]<<endl;
}
return 0;
}
我得到以下輸出:
Value of a[0] is: 10 same as 10 Address is: 0x7fff5bf29b1c , same as 0x7fff5bf29b1c
Value of a[1] is: 20 same as 20 Address is: 0x7fff5bf29b20 , same as 0x7fff5bf29b20
Value of a[2] is: 30 same as 30 Address is: 0x7fff5bf29b24 , same as 0x7fff5bf29b24
Value of line[0] is: H same as H Address is: Hello , same as Hello
Value of line[1] is: e same as e Address is: ello , same as ello
Value of line[2] is: l same as l Address is: llo , same as llo
Value of line[3] is: l same as l Address is: lo , same as lo
Value of line[4] is: o same as o Address is: o , same as o
當我改變這一行:
cout<<" Address is: "<<ptr2line+i<<" , same as "<<&line[i]<<endl;
到:
cout<<" Address is: "<<&ptr2line+i<<" , same as "<<&line[i]<<endl;
我得到這樣的輸出:
Value of line[0] is: H same as H Address is: 0x7fff5054bad0 , same as Hello
Value of line[1] is: e same as e Address is: 0x7fff5054bad8 , same as ello
Value of line[2] is: l same as l Address is: 0x7fff5054bae0 , same as llo
Value of line[3] is: l same as l Address is: 0x7fff5054bae8 , same as lo
Value of line[4] is: o same as o Address is: 0x7fff5054baf0 , same as o
在這種情況下 地址0x7fff5054bad0相當於「你好」 0x7fff5054bad8對應值「ELLO」等。
創建存儲字符串每個字符地址的指針的正確方法是什麼?
解決方案
一種方法以可視化的指針是對printf使用代替
printf("Value of line[%d] is: %c same as %c, Address is: %p, same as %p\n", i, line[i], *(ptr2line+i),ptr2line+i,&line[i]);
,得到所需的輸出
Value of line[0] is: H same as H, Address is: 0x7fff54ce6ade, same as 0x7fff54ce6ade
Value of line[1] is: e same as e, Address is: 0x7fff54ce6adf, same as 0x7fff54ce6adf
Value of line[2] is: l same as l, Address is: 0x7fff54ce6ae0, same as 0x7fff54ce6ae0
Value of line[3] is: l same as l, Address is: 0x7fff54ce6ae1, same as 0x7fff54ce6ae1
Value of line[4] is: o same as o, Address is: 0x7fff54ce6ae2, same as 0x7fff54ce6ae2
另一種解決方案已經概述通過下述@Daniel怨婦。