2

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,460
  • 3
  • 16
  • 41

2 Answers2

3

You can make use of a compound literal. Something like

function((int []){3, -11, 0, 122});
Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
2

You could pass array as compound literal as below.

function((int []){3, -11, 0, 122});
kiran Biradar
  • 12,460
  • 3
  • 16
  • 41