今天就跟大家聊聊有关怎么在C++中动态内存分配,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
按需分配,根据需要分配内存,不浪费。
内存拷贝函数void* memcpy(void* dest, const void* src, size_t n);
从源src中拷贝n字节的内存到dest中。需要包含头文件#include <string.h>
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int* b;
b = new int[15];
//从a拷贝10 * 4字节的内存到b
memcpy_s(b, sizeof(int) * 10, a, sizeof(int) * 10);
//进行赋值
for(int i = sizeof(a) / sizeof(a[0]); i < 15; i++){
*(b + i) = 15;
}
for (int i = 0; i < 15; i++) {
printf("%d ", b[i]);
}
return 0;
}
输出结果:
1 2 3 4 5 6 7 8 9 10 15 15 15 15 15
被调用函数之外需要使用被调用函数内部的指针对应的地址空间
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//定义一个指针函数
void* test() {
void* a;
//分配100*4个字节给a指针
//mallocC语言的动态分配函数
a = malloc(sizeof(int) * 100);
if (!a) {
printf("内存分配失败!");
return NULL;
}
for (int i = 0; i < 100; i++)
{
*((int*)a + i) = i;
}
return a;
}
int main() {
//test()返回void*的内存,需要强转换
int* a = (int*)test();
//打印前20个
for (int i = 0; i < 20; i++) {
printf("%d ", a[i]);
}
//C语言的释放内存方法
free(a);
return 0;
}
输出结果:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
此处在main函数中使用了在test()函数中分配的动态内存重点地址。
也可以通过二级指针来保存,内存空间:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//定义一个指针函数
void test(int **a) {
*a = (int*)malloc(sizeof(int) * 100);
if (!*a) {
printf("内存分配失败!");
exit(0);
}
for (int i = 0; i < 100; i++)
{
*(*a + i) = i;
}
}
int main() {
//test()返回void*的内存,需要强转换
int* a;
test(&a);
//打印前20个
for (int i = 0; i < 20; i++) {
printf("%d ", a[i]);
}
free(a);
return 0;
}
突破栈区的限制,可以给程序分配更多的空间。
栈区的大小有限,在Windows系统下,栈区的大小一般为1~2Mb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
void test() {
//分配一个特别大的数组
int a[102400 * 3];// 100k * 3 * 4 = 1200K
a[0] = 0;
}
int main() {
test();
return 0;
}
点运行会出现Stack overflow的提示(栈区溢出!)。
修改:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
void test() {
//在堆中分配一个特别大的数组1G
//在Windows 10 系统限制的堆为2G
int* a = (int*)malloc(1024 * 1000 * 1000 * 1); //1G
a[0] = 0;
}
int main() {
test();
return 0;
}
成功运行!但是当分配两个G的动态内存时,就会报错,这个时候分配失败,a = NULL;
1、按需分配,根据需要分配内存,不浪费。
2、被调用函数之外需要使用被调用函数内部的指针对应的地址空间。
3、突破栈区的限制,可以给程序分配更多的空间。
看完上述内容,你们对怎么在C++中动态内存分配有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。