C++ new分配与再分配内存&&C malloc、calloc分配,realloc再分配内存

1、检测C++ new 是否具有再分配
2、检测C realloc再分配

3、代码

#include 
#include 

using namespace std;

void input(int * &s,int start,int num) {
	cout << "input:" << endl;
	int temp;
	for (int i = start-1; i < num; i++) {
		scanf_s("%d", &temp);
		s[i] = temp;
	}
}

void output(int *s,int num) {
	cout << "data:" << endl;
	for (int i = 0; i < num; i++) {
		printf("%d ", s[i]);
	}
	printf("\n");
}
int main() {
	//C
	cout << "测试C" << endl;
	//calloc
	cout << "初始化calloc(num:5)" << endl;
	int *ex1 = (int *)calloc(5, sizeof(int));
	input(ex1,1,5);
	output(ex1,5);
	//realloc
	cout << "再分配realloc(addnum:5)" << endl;
	ex1 = (int *)realloc(ex1,10 * sizeof(int));
	input(ex1, 6, 10);
	output(ex1, 10);
	//malloc
	cout << "初始化malloc(num:5)" << endl;
	int *ex2 = (int *)malloc(sizeof(int) * 5);
	input(ex2, 1, 5);
	output(ex2, 5);
	//realloc
	cout << "再分配realloc(addnum:5)" << endl;
	ex2 = (int *)realloc(ex2, 10 * sizeof(int));
	input(ex2, 6, 10);
	output(ex2, 10);
	free(ex1);
	free(ex2);
	
	//C++
	cout << "测试C++" << endl;
	cout << "初始化(num:5)" << endl;
	int *ex3 = new int[5];
	for (int i = 0; i < 5; i++) {
		cin >> ex3[i];
	}
	for (int i = 0; i < 5; i++) {
		cout << ex3[i] << " ";
	}
	cout << endl;
	cout << "new再分配(addnum:5)" << endl;
	ex3 = new int[10];
	for (int i = 5; i < 10; i++) {
		cin >> ex3[i];
	}
	for (int i = 0; i < 10; i++) {
		cout << ex3[i] << " ";
	}
	delete[] ex3;
	cout << endl;
	system("pause");
}

4、结果
C++ new分配与再分配内存&&C malloc、calloc分配,realloc再分配内存_第1张图片
C++new 并不能执行再分配

你可能感兴趣的:(C++ new分配与再分配内存&&C malloc、calloc分配,realloc再分配内存)