typedef

Hello Everybody,

can you please explain working of the following to alogo or code snippet..

1. Dynamic Double Dimensional Array
[code]
typedef int DDim[5];
DDim *p;
p=malloc(//assigning mem dynamically);
[/code]

and
2. Rounding Off
[code]
#define x (int)(x+0.5)
[/code]

Waiting for replies...............
Thank you

Comments

  • : 1. Dynamic Double Dimensional Array
    : [code]:
    : typedef int DDim[5];
    : DDim *p;
    : p=malloc(//assigning mem dynamically);
    : [/code]:

    That code is rather hard to grasp, but what it likely does is to create a 2-dimensional array in a somewhat clever way. The advantage of this code is that the 2D array will be allocated in one big chunk of data. The most common method for 2D arrays is to use pointer-to-pointer, which is a poor method. This link explains the topic a lot better than I do:

    http://c-faq.com/aryptr/dynmuldimary.html



    : #define x (int)(x+0.5)

    That code doesn't make sense. Perhaps you meant something like this

    #define round(x) ((double)(int)(x + 0.5))

    That would be a poor man's float rounding routine. x is assumed to be floating point. The macro would be called like this:

    float my_float = 5.55;
    my_float = round(my_float);

    The compiler will turns this into the expression

    ((double)(int)(5.55 + 0.5))
    which is

    ((double)(int)(6.05)

    When you typecast float to int, the decimals are removed and we get the number 6. The final cast to double should be there to turn the result back into float.

    [italic]However[/italic], macros are the tools of the devil and should never be used! Seriously: never. They are very error-prone, have plenty of undefined behavior in the standard, and they are a pain to understand & debug. Avoid them like the plauge.

    A much much better way to achieve the same is a function:

    [code]double round (double x)
    {
    return (double)(int)(x + 0.5);
    }[/code]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion