在使用char* 傳遞參數(shù)的時(shí)候,以為char* 傳遞的是指針傻粘;
#include <iostream>
#include<string>
#include <cstring>
#include<vector>
using namespace std;
void printNoref(char * s){
cout<<"非引用傳值函數(shù)中s 地址:"<<&s<<endl;
cout<<"s 指向的地址:"<<(int*)s<<endl;
s++;
cout<<"str:"<<s<<endl;
}
void printref(char *& s){
cout<<"非引用傳值函數(shù)中s 地址:"<<&s<<endl;
cout<<"s 指向的地址:"<<(int*)s<<endl;
(s)++;
cout<<"ref str:"<<s<<endl;
}
int main() {
string s ( "123456789");
char* str = new char[s.size() + 1];
strcpy(str, s.c_str());
// 真實(shí)地址
cout<<"真實(shí) str 地址:"<<&str<<endl;
cout<<"str 指向的地址:"<<(int*)str<<endl;
//非引用傳值
printNoref(str);
cout<<"str 指向的地址:"<<(int*)str<<" 值 str:"<<str<<endl;
cout<<"================"<<endl;
// 引用傳值
printref(str);
cout<<"str 指向的地址:"<<(int*)str<<" 值 str:"<<str<<endl;
return 0;
}
結(jié)果:
真實(shí) str 地址:0x7ffcf092ee08
str 指向的地址:0x1481c20
非引用傳值函數(shù)中s 地址:0x7ffcf092ede8
s 指向的地址:0x1481c20
str:23456789
str 指向的地址:0x1481c20 值 str:123456789
================
引用傳值函數(shù)中s 地址:0x7ffcf092ee08
s 指向的地址:0x1481c20
ref str:23456789
str 指向的地址:0x1481c21 值 str:23456789
-
char * s
傳遞的是s地址中存儲(chǔ)的指針地址的復(fù)制每窖, -
char*& s
傳遞的是指向s真實(shí)地址的指針帮掉;