使用指针来实现变长数组(VLA)

实现代码:

#include <cstdio>
#include <cstdlib>
void usePtoImplementVLA(int SIZE)
{
	scanf("%d", &SIZE);
	int *pVLA = (int *)malloc(sizeof(int) * SIZE);
	
	for (int i = 0; i < SIZE; i++)
		scanf("%d", &pVLA[i]);
	
	free(pVLA);
}

实现思路:

1、输入创建指针大小SIZE
2、使用sizeof函数得出需要的空间大小。例:输入10sizeof(int) * SIZE得出40。
3、使用malloc函数动态分配内存空间。(注:一般的时候,malloc函数与free函数连用)
4、用for循环输入每一个数据。
5、用free函数释放内存空间。

参考资料:

cplusplus-malloc
百度百科-malloc
cppreference-sizeof

原文地址:https://www.cnblogs.com/JingWenxing/p/10126561.html