#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 等运算符一定要测试非空。