0

HELP! Arrays in c++

when we work with an anrray, its size to be constant. is it possible to get an integer number from the user and fix it as a size of array? int i, cin>>i; int arr[i]; I want to use like above

14th Mar 2017, 10:38 AM
Abu-Bakr Jabbarov
Abu-Bakr Jabbarov - avatar
3 Answers
+ 3
Yes it is possible by allocating memory to arrays dynamically at runtime. There are two keywords that help in doing so. 1. new - allocates memory 2. delete - releases allocated memory. Following example may help you to understand the concept of dynamic arrays #include <iostream> #include <stdlib.h> using namespace std; int main (void){ // a pointer to int type is declared to which will point to the allocation for n elements int *ptr; int n,big; //read no of element cout<<"Enter no of elements: ";cin>>n; // Tries to allocated memory for n elements of type int // if succeeded, address of first element is assigned to the // pointer variable otherwise NULL is assigned ptr = new int [n]; //validate allocation - NULL value means allocation failed if (ptr==NULL){ cerr<<"Failed to allocate memory"; return -1; } /* Since allocation has been successful. Now the pointer ptr can be accessed as normal array */ int x; for (x=0;x<n;x++){ cout<<"Enter " <<(x+1)<<" value: "; cin>>ptr[x]; } big=ptr[0]; for (x=1;x<n;x++){ if (big<ptr[x]){ big = ptr[x]; } } cout<<"Biggest value is "<<big; //Memory allocated has to be released delete statement does the same delete ptr; }
14th Mar 2017, 10:52 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 3
Good answer @Devender! Just one small bug at the end - it must be (since you allocated an array): delete[] ptr;
14th Mar 2017, 1:55 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
@Ettienne thanks for debugging out the error.
14th Mar 2017, 2:36 PM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar