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});?

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44

2 Answers2

6

You can make use of a compound literal. Something like

function((int []){3, -11, 0, 122});
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
4

You could pass array as compound literal as below.

function((int []){3, -11, 0, 122});
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44