You are here:

C++/C++ dynamic memory allocation


Hi Mr. Dharmendra
   Many thanx for ur reply. I tried ur solution.
It worked properly. but i get stuck in new problem.
I started as :

int **a;
a=new int*[200];
int i=0,j=0;
  a[i]=new in[512];
// Now when i tried to assign some random value to each of them
// using rand()%.. defined in stlib.h as:


It was giving unexpected runtime error , i was unable to trace it.
Plz help me
Thanking you.

Followup To
Question -
Hi, I am a new C++ programmar. I want to know how to dynamically allocate
memory for 2 dimentional array.
E.g. int a[100][400];
how can be such memory be allocated using 'new' operator.
(i'll thankful if u tell how to do using malloc)

thanking you
Answer -
#include <iostream>
using namespace std;

int main()
  int **x=NULL;
  x = new int * [10];
// x = (int **) malloc (sizeof(int *) * 10);
  for (int i = 0 ; i < 10; i++)
     x[i] = new int [10];
// x[i] = (int *) malloc (sizeof(int) * 10);
  for (i = 0 ; i < 10; i++)
     delete [] x[i];
// free x[i];
  delete [] x;
// free delete x;
  return 0;

problem is with the following while loop:
a[i]=new in[512];

Please do not use the post increment operator there as it is missing out i = 0 and is starting from i = 1. you would be suprised as it is post increment operator not pre one but that explanation is also a big one so some other point of time.


All Answers

Answers by Expert:

Ask Experts


Dharmender Rai


I can answer general and system level C/C++ questions.


I have 5 years of experience in C++.

©2017 All rights reserved.