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);
}
Yes. You can. In C99/11 you can do by using 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With