[prog] use of the new and delete operator...

Tim King timk at jtse.com
Fri Jul 13 15:33:41 UTC 2007


programming-request at linuxchix.org wrote:


>   struct sol{
>   .
>   .
>   .
>   };
>    
>   sol S;
>    
>   S *sco = NULL; 
Hi, Sena. Maybe I don't understand what you mean. If it doesn't work, 
what /does/ it do? Does it compile? Does it run out of memory? Does it 
lock up? Does it crash?

The above should not even compile, because it is syntactically 
incorrect. When the compiler sees "S *sco," it thinks that means "take S 
(which is of type sol) and multiply it by sol." But since sco is not 
declared, it doesn't know what type it is and should give an error at 
that point.

For example, I tried in KDevelop (using the "Hello World" template):
> struct sol {
> int foo;
> int bar;
> };
>
> int main(int argc, char *argv[])
> {
> for (int num_iterations = 0; num_iterations < 1000000; ++ 
> num_iterations) {
> int num = 100;
> sol S;
> S* sco = new sol[num];
> delete [] sco;
> }
>
> cout << "Hello, world!" << endl;
>
> return EXIT_SUCCESS;
> }
When I tried to build this, I got:
> /home/timk/temp/new-delete-test/new_delete_test/src/new_delete_test.cpp:41: 
> error: ‘sco’ was not declared in this scope
(Line 41 is the "S* sco" line.)

To fix this, I changed the code to:
> int num = 100;
> sol* sco = new sol[num];
> delete [] sco;
This builds fine and runs with no errors.

-TimK

-- 
http://LucrativeWebDesign.com/
http://www.JTimothyKing.com/blog/


More information about the Programming mailing list