Memory allocation

Started by
12 comments, last by Leadorn 21 years, 9 months ago
NULL == 0;
It''s not a memory address. It means empty. if you do this:

a_ptr = new int* [10];

that means you''re allocating 10 pointers to int which are not yet initialized. so, you have to initialize them again:

for (int i=0; i<10; i++)
a_ptr = new int [100];

by doing this, each pointer in a_ptr points to an array of int of size 100.

if you want to delete it, you do it in the reverse order:
for (int i=0; i<10; i++)
if (a_ptr != NULL) delete [] a_ptr;<br>delete [] a_ptr;<br><br>however, people usually do it this way:<br><br>for (int i=0; i<10; i++) {<br> if (a_ptr != NULL) {<br> delete [] a_ptr;<br> a_ptr = NULL;<br> }<br>}<br><br>delete [] a_ptr;<br>a_ptr = NULL;<br><br>You don''t have to set it equal to NULL, but it''s just the good way to do it. Sometimes, you''ll also find some benefits by doing that, so it''s a good practice.<br><br> </i> <br><br><hr><i>My compiler generates one error message: "Doesn''t compile."<br>-Albert Tedja-</i>
My compiler generates one error message: "does not compile."
Advertisement
i wonder...how come part of my post is in italic?? oh, i see. some parts are recognized as tags. btw, here's the complete code from the above post. some of them are removed accidentally.


    a_ptr = new int* [10];for (int i=0; i<10; i++)a_ptr[i] = new int [100];//if you want to delete it, you do it in the reverse order:for (int i=0; i<10; i++)if (a_ptr[i] != NULL) delete [] a_ptr[i];delete [] a_ptr;//however, people usually do it this way:for (int i=0; i<10; i++) {if (a_ptr[i] != NULL) {delete [] a_ptr[i];a_ptr[i] = NULL;}}delete [] a_ptr;a_ptr = NULL;    



[edited by - nicho_tedja on June 25, 2002 5:23:33 AM]

[edited by - nicho_tedja on June 25, 2002 5:24:19 AM]
My compiler generates one error message: "does not compile."
quote:Original post by nicho_tedja
however, people usually do it this way:

Which people? Nobody I know does it that way.

Why do it this way?
int **pointer_array = new int *[10];


what is the difference between them?


a_ptr = new int* [10];
that means you''re allocating 10 pointers to int which are not yet initialized. so, you have to initialize them again:




This topic is closed to new replies.

Advertisement