代碼段
#include <iostream>
#include <string.h>
using namespace std;
void mal(char *q)
{
q=new char[100];
}
int main()
{
char *p=NULL;
mal(p);
_ASSERT(p!=NULL);
strcpy(p,"this is a test");
cout<<p<<endl;
}
這個程序是有錯誤的,程序會崩潰。原因,因爲p指針並沒有申請到內存。
p指針初始化爲NULL,然後再執行mal()函數的時候,只是拷貝了一份實參的參數,q也爲NULL,然後指針q申請內存。但這並沒有反映在p上,p同樣爲NULL
然後導致沒有申請到內存,執行strcpy()時導致程序崩潰。(可以在strcpy之前加斷言測試一下_ASSERT(p!=NULL))
所以我們應該傳遞指針的地址或者是指針的引用
傳引用
#include <iostream>
#include <string.h>
using namespace std;
void mal(char *&q)
{
q=new char[100];
}
int main()
{
char *p=NULL;
mal(p);
_ASSERT(p!=NULL);
strcpy(p,"this is a test");
cout<<p<<endl;
}
#include <iostream>
#include <string.h>
using namespace std;
void mal(char **q)
{
*q=new char[100];
}
int main()
{
char *p=NULL;
mal(&p);
_ASSERT(p!=NULL);
strcpy(p,"this is a test");
cout<<p<<endl;
}