A typedef can resolve to one of two types, but both seem impossible to me

80 views Asked by At

I see a type (fb_t) defined like so in the RELIC library (docs here https://code.google.com/p/relic-toolkit/downloads/list):

#if ALLOC == AUTO
typedef align dig_t fb_t[FB_DIGS + PADDING(FB_BYTES)/(FB_DIGIT / 8)];
#else
typedef dig_t *fb_t;
#endif

(align is defined as /* empty */, if it matters)

So it's a pointer, or it's an array. But if it's an array, then how would this function work? (from relic-doc/html/df/d96/relic__fb__util_8c_source.html#l00080)

void fb_copy(fb_t c, const fb_t a) {
    for (int i = 0; i < FB_DIGS; i++) {
        c[i] = a[i];
    }
}

And if it's a pointer, how would this code work (since they're uninitialized pointers)?

//create two variables 
fb_t source, target;
fb_copy(target,source); //and copy one to the other

Both are run from the same computer. The sizeof(fb_t) on this computer is 16.

2

There are 2 answers

0
AudioBubble On BEST ANSWER

But if it's an array, then how would this function work?

Very well, thanks. Why wouldn't it work?

And if it's a pointer, how would this code work (since they're uninitialized pointers)?

If passed uninitialized pointers, it wouldn't work (it would cause undefined behavior instead).

But: I strongly suspect that, since the typedef depends on an #ifdef (which seems to control automatic vs. dynamic memory allocation), this case is covered in a safe way too (i. e. whichever part of the code used uninitialized fb_t objects would be excluded from the compilation when fb_t is defined as a pointer.)

0
sanjeev mk On

The function fb_copy above, works correctly irrespective of fb_t being an array or pointer. And that's because of the equivalence of arrays and pointers.

Consider this (read the comments):

    int a[10];
    int *ip;

    ip = a; 
    // this assignment is as if you have written ip = &a[0]
    // the first facet of equivalence

The second is, you can use the [i] syntax of accessing array elements, with pointers as well.

     int a = ip[3]
     //it is just as if you had written *(ip + 3)

By equivalent , we mean that though pointers and arrays are different, pointer arithmetic and array indexing are equivalent and tied.

So in this case that you've pointed out, if that function is passed initialized pointers , it does the equivalent of *(c+i) = *(a+i)