4

How can we pass an array directly to a function in C?

For example:

#include <stdio.h>

void function(int arr[]) {};

int main(void) {
    int nums[] = {3, -11, 0, 122};
    function(nums);
    return 0;
}

Instead of this, can we just write something like function({3, -11, 0, 122});?

6
  • One option is to wrap the array inside a struct: struct foo { int arr[10]; }; struct foo wrapped = {{3, -11, 0, 122}}; fx(wrapped); Commented Jan 11, 2021 at 8:06
  • @pmg but that still uses an intermediate variable Commented Jan 11, 2021 at 8:07
  • Ah! Didn't read the question title with enough attention; anyway leaving the comment here :-) Commented Jan 11, 2021 at 8:08
  • @pmg Not your fault sir, I expanded the title based on my understanding of the question. the initial version had no mention of that. Apologies. Commented Jan 11, 2021 at 8:10
  • "can we just write something like" - What happened when you tried? Commented Jan 11, 2021 at 8:11

2 Answers 2

7

You can make use of a compound literal. Something like

function((int []){3, -11, 0, 122});
Sign up to request clarification or add additional context in comments.

2 Comments

One of those things that work in C but not C++, I think.
@dxiv: it works in C99 and later, but not in C++ (yet?).
5

You could pass array as compound literal as below.

function((int []){3, -11, 0, 122});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.