Hacker News new | ask | show | jobs
by qwertzuiop 3226 days ago
Why is declaration wrong? I am in process of learning C, and I don't see anything wrong.
3 comments

You shouldn't new or malloc unless you need to. The more you allocate the more you leak.

Just stack/automatically allocate the resource and take the address with & then pass the pointer around. Because the data is automatically cleaned up you know you won't have any leaks (and certain whole other classes of bugs).

EDIT - Consider:

    int myDictLen = 0;
    int* myDictLenPtr = &myDictLen;

    /* now you can pass around the pointer myDictLenPtr 
       to functions that can used an int* and it will be
       available in this scope and automatically cleaned 
       up for you. */
If a function takes an argument of type pointer-to-int, you can simply pass a reference to an int variable on the stack with "&myInt". The code in question seems to be using heap allocation just to get a pointer-to-int, which makes one suspect that the author doesn't know about the & operator.
There is nothing wrong with the syntax itself. Its simply that it's usually preferable to allocate variables on the stack. To do this, you would do:

int var_a = 5;

and use &var_a when you want to acess that variable as a pointer within that scope. Not only is this more efficient, it is much easier to read.