目錄
動態內存的傳遞方式
先看一個錯誤程序:
#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>