#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
void getMemory(int * p)
{
p = (int*)malloc(100);
*p = 5;
cout<<p<<endl;
//return p;
}
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
int* str = NULL;
cout<<str<<endl;
getMemory(str);
// strcpy(str,"hello");
//*str = 789;
cout<<str<<endl;
return 0;
}
上面的程序本來打算讓函數 gerMemory 來申請一段內存。但是。。。str 本來是指向NULL。也就是說 str的值其實是0000000.通過實參到形參p .p的值也是00000。p通過malloc改變後,並不能讓str 改變。所以程序出了問題。
另外。malloc new 等運算符一定要測試非空。