目录
动态内存的传递方式
先看一个错误程序:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
void getmemory(char * p, int num)
{
p = (char *)malloc(sizeof(char) *num);
};
int main()
{
char *str = NULL;
getmemory(str, 10);
strcpy(str, "hello");
printf("str:%s\n", str);
free(str);
str = NULL;
system("pause");
return 0;
}
上面的代码一运行就出错,原因是,在函数中创建的动态内存p,并没有与函数外的str衔接上,完全没关系,所以,str一直是空的。那么怎么改呢?
采用引用作为参数传递
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
void getmemory(char * &p, int num) //传进去一个引用
{
p = (char *)malloc(sizeof(char) *num);
};
int main()
{
char *str = NULL;
getmemory(str, 10);
strcpy(str, "hello");
printf("str:%s\n", str);
free(str);
str = NULL;
system("pause");
return 0;
}
运行如下:
采用二维指针作为参数传递
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
void getmemory(char **p, int num) //这里接收一个指针
{
*p = (char *)malloc(sizeof(char) *num);
};
int main()
{
char *str = NULL;
getmemory(&str, 10); //传进去一个指针
strcpy(str, "hello");
printf("str:%s\n", str);
free(str);
str = NULL;
system("pause");
return 0;
}
采用返回对内存指针作为参数传递
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
char *getmemory(int num)
{
char *p = (char *)malloc(sizeof(char) *num);
return p;//返回一个指针
};
int main()
{
char *str = NULL;
str = getmemory(10);//用指针来接收
strcpy(str, "hello");
printf("str:%s\n", str);
free(str);
str = NULL;
system("pause");
return 0;
}
解决strcpy函数使用时提示unsafe的方法
在程序最开头添加两行如下代码即可:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>