Monday, April 5, 2010

Allocating memory

"C++" I answered with all the confidence I had, when I was asked about my strength in my first interview. So the interviewer asks me how to allocate memory to an array in C++.

"double arr[10]" I wrote on paper. He asked me "are you sure?", I said "yes". He said "are you sure there isn't any other way?" .. I said "yes.. i am pretty much sure"... and I was rejected in the interview.

Well, for all those who are thinking that i might have been right ( actually I could have been given the benefit of the doubt ), there is another way of allocating memory. Called Dynamic memory allocation ( all the experienced people might be yawning but read on for some surprise).

unsigned int yourvalue = GetUserInputValue();
double *arr = new double[yourvalue]; --------> dynamic memory allocation

Now, for a question for experienced programmer, how do you dynamically allocate memory to a two dimensional array? trust me I have asked this question to people with 4 yrs of experience but seldom I have got the right answer.

double **arr;
*arr = new double*[10] -----------------> allocate the rows

for(int i =0; i <>
arr[i] = new double[10] -----------------> allocate the columns.

so this way we allocate, a two dimensional array of 10 rows and 10 columns.

Now a question so you guys can leave a comment here..... How would you delete the above allocated two dimensional array?

No comments:

Post a Comment