Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array as function argument without defining a variable [duplicate]

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

like image 860
Abhigyan Kumar Avatar asked Oct 20 '25 14:10

Abhigyan Kumar


2 Answers

You can make use of a compound literal. Something like

function((int []){3, -11, 0, 122});
like image 92
Sourav Ghosh Avatar answered Oct 22 '25 04:10

Sourav Ghosh


You could pass array as compound literal as below.

function((int []){3, -11, 0, 122});
like image 38
kiran Biradar Avatar answered Oct 22 '25 02:10

kiran Biradar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!