You are not logged in. Please login at www.codechef.com to post your questions!

×

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

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

asked 14 Mar '15, 15:34

ajaygepal's gravatar image

0★ajaygepal
1
accept rate: 0%


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\n");
        return 1;
    }

    *ptr_one = 25;
    printf("%d\n", *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\n";
cin >> n;
pointer = new int[n]; 
cout << "Enter " << n << " integers\n"; 
for ( c = 0 ; c < n ; c++ )
    cin >> pointer[c]; 
cout << "Elements entered by you are\n";
for ( c = 0 ; c < n ; c++ )
    cout << pointer[c] << endl;
delete[] pointer;
return 0;

}

link

answered 14 Mar '15, 16:24

utkarsh13's gravatar image

4★utkarsh13
2303717
accept rate: 6%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×22

question asked: 14 Mar '15, 15:34

question was seen: 828 times

last updated: 14 Mar '15, 16:24