Re: Passing aggregate directly to function

Discussion in 'C Programming' started by James Kuyper, Jun 27, 2013.

  1. James Kuyper

    James Kuyper Guest

    On 06/27/2013 10:55 AM, Guillaume Dargaud wrote:
    > Hello all,
    > I have a colleague who was trying to do something like this, it wouldn't
    > compile and I couldn't come with a reason as to _why_ you can't do it:
    >
    > void Func(char* Array[]) { ... }
    >
    > Func( {"aaa", "bb"} );


    In other contexts, {"aaa", "bbb"} could be the initializer of an array
    of char* objects. It could also be the initializer for a two-dimensional
    array of char, so long as the second dimension is at least 3. However,
    it is not, itself, an array, and can't be used as such. In this context,
    it's just a syntax error.

    > Func( {"c"} );
    > ...
    >
    > Using an intermediate variable of course works:
    > char* tmp[]={"aaa", "bb"};
    > Func( tmp );
    >
    > So, is there any way to do it directly ? And if not why ?


    C99 added the concept of compound literals, which is basically an
    extension of the idea of string literals, which allows you to do
    something similar to what you want, with slightly different syntax:

    Func((char *[]){"aaa", "bbb"});

    Internally, the meaning of the above code is exactly the same as your
    version using tmp, except that in this case, the temporary object is
    nameless. The temporary object's lifetime ends at the end of the
    enclosing block. One reason why the syntax is different can be
    understood if you consider this alternative:
    Func2((char[][4]){"aaa", "bbb"});

    This is equivalent to
    char tmp[][4] = {"aaa", "bbb"};
    Func2(tmp);

    which is significantly different than the other version. With the syntax
    you're suggesting, it wouldn't be possible to make that distinction.
    James Kuyper, Jun 27, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. rickman
    Replies:
    3
    Views:
    4,969
    rickman
    Jul 15, 2003
  2. aggregate operator

    , Jul 11, 2005, in forum: VHDL
    Replies:
    3
    Views:
    1,358
  3. Unforgiven
    Replies:
    5
    Views:
    533
    Samee Zahur
    Apr 26, 2005
  4. Aaron

    ASP Aggregate Function

    Aaron, Dec 12, 2006, in forum: ASP General
    Replies:
    3
    Views:
    245
    Mark McGinty
    Dec 15, 2006
  5. Ike Naar

    Re: Passing aggregate directly to function

    Ike Naar, Jun 27, 2013, in forum: C Programming
    Replies:
    2
    Views:
    179
    Keith Thompson
    Jun 27, 2013
Loading...

Share This Page