how can we controle array size at run time in c++ ???

dev-c-plus-plus

#1

how can we controle array size at run time in c++ ???


#2

To control array size at runtime we use dynamic allocation.

In C
we use malloc and free.
The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory.When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free.

#include<stdio.h>

int main()
{
	int *ptr_one;

	ptr_one = (int *)malloc(sizeof(int));

	if (ptr_one == 0)
	{
		printf("ERROR: Out of memory

");
return 1;
}

	*ptr_one = 25;
	printf("%d

", *ptr_one);

	free(ptr_one);

	return 0;
}

In C++ we use new and delete.
With the operator new we can request a piece of memory. A data type must follow the new operator. It is also possible to request more than one element by using brackets []. The result of a new operation is a pointer to the beginning of the memory block.If a memory request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the operator delete.

#include <iostream>
using namespace std; 
int main()
{
int n, *pointer, c;
cout << "Enter an integer

";
cin >> n;
pointer = new int[n];
cout << "Enter " << n << " integers
";
for ( c = 0 ; c < n ; c++ )
cin >> pointer[c];
cout << "Elements entered by you are
";
for ( c = 0 ; c < n ; c++ )
cout << pointer[c] << endl;
delete[] pointer;
return 0;
}