Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Send array to function without declaring it [duplicate]

Is it possible to send an array to a C function without declaring/defining it first?

This is possible with integers.

int add(int a, int b) {
    return (a + b);
}

void main(void) {
    int c;
    int a=1, b=2;

    /* With declaring (works fine)*/
    c = add(a, b);

    /* Without declaring (works fine)*/
    c = add(1, 2);
}

Is there anything along the lines of this for arrays?

#include <stdio.h>

void print_int_array(int *array, int len) {
    int i;
    for (i = 0; i < len; i++)
        printf("%d -> %d\n", i, *array++);
}

void main(void) {
    int array[] = {1, 1, 2, 3, 5};

    /* With declaring (works just fine) */
    print_int_array(array, 5);

    /* Without declaring (fails to compile) */
    print_int_array({1, 1, 2, 3, 5}, 5);
}
like image 388
ryanmjacobs Avatar asked Aug 29 '26 03:08

ryanmjacobs


1 Answers

Yes. You can. In C99/11 you can do by using compound literals:

C11: 6.5.2.5 Compound literals:

A postfix expression that consists of a parenthesized type name followed by a braceenclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.99).

print_int_array((int[]){1, 1, 2, 3, 5}, 5);  

99) Note that this differs from a cast expression. For example, a cast specifies a conversion to scalar types or void only, and the result of a cast expression is not an lvalue.

like image 71
haccks Avatar answered Aug 31 '26 17:08

haccks



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!