【黑马教程】【指针专题】在子函数中使用malloc申请内存,错误方式和正确的方式
作者:互联网
#include<iostream>
using namespace std;
#include<string>
//Define a structure
void getMem(char *ptr)
{
ptr = (char*)malloc(sizeof(char)*100);
if(nullptr == ptr)
{
cout<<"getMem ptr is nullptr"<<endl;
return;
}
strcpy_s(ptr, 9, "abcd");
cout << "getMem ptr:" << ptr<< endl;
}
int main(void)
{
char* ptr = nullptr;
getMem(ptr);
if (nullptr == ptr)
{
cout << "main ptr is nullptr";
}
else
{
cout << "main ptr:" << ptr << endl;
}
system("pause");
return 0;
}
/*
getMem ptr:abcd
main ptr is nullptr请按任意键继续. . .
*/
标签:malloc,char,子函数,内存,getMem,include,ptr 来源: https://blog.csdn.net/hfut31415926/article/details/121806927