1

I want to be able to pass a variable number of objects in C to a function, by wrapping it in an array. As an example:

void test(int arr[]) {}

int main (int argc, char** argv) {
    test({1, 2});
}

But I'm not certain how to go about creating an in-line array, and googling the problem leads to a lot of unrelated results.

I've also tried these variations:

test(int[]{1, 2});
test(int[2]{1, 2});

However have not found any reasonable way to create this. How is this possible in C?

As a note, I cannot use varargs.

Edit:

The code used and the compiler error:

void test(int ex[]) {}

int main() {
    test(int[]{1, 2});
}

test.c:4:10: error: expected expression before 'int'

3
  • 1
    what problem (exactly) did you encounter? Did it fail to compile? (then you must post the compiler error!) Did it crash at Runtime? (then you must describe the runtime crash! What type? what message? what line?) Commented May 9, 2014 at 15:20
  • Adding to question for posterity Commented May 9, 2014 at 15:24
  • What OS are you using? Note that the Visual Studio C Compiler is C89 since William III decided to ignore C99 and everything it followed, where support for more literals was added. Commented May 9, 2014 at 15:27

2 Answers 2

3

Your first attempt was very close - all you needed is to add parentheses:

test((int[]){1, 2});
//   ^     ^
// Here    |
//     and here

This is the compound literal syntax for arrays, which is added in C99. Similar syntax is available for structs, and it also requires parentheses around the type name.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, casting seems to have fixed this.
@Rogue This looks like casting, but it's the compound literal syntax of C99 that looks exactly like casting followed by a curly brace.
0
void test(int arr[])
{
    /* some body */
}

int main(void)
{
    int array[] = {1, 2};
    test(array);
    return 0;
}

1 Comment

You might also provide a sentinel or an array count somehow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.