C - 将数组发送到函数而不声明它

rya*_*obs 1 c arrays declaration

是否可以将数组发送到C函数而不先声明/定义它?

这可以用整数来实现.

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);
}
Run Code Online (Sandbox Code Playgroud)

对阵列有什么一点吗?

#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);
}
Run Code Online (Sandbox Code Playgroud)

oua*_*uah 5

是的,从 c99 开始,使用复合文字是可能的:

print_int_array((int [5]) {1, 1, 2, 3, 5}, 5);
Run Code Online (Sandbox Code Playgroud)

( ){ }是复合文字运算符。复合文字提供了一种指定聚合或联合类型的未命名常量的机制。(非常量)复合文字是可修改的。


hac*_*cks 5

是.您可以.在C99/11中,您可以使用复合文字:

C11:6.5.2.5复合文字:

后缀表达式由带括号的类型名称后跟一个大括号的初始值设定项列表组成,是一个复合文字.它提供了一个未命名的对象,其值由初始化列表给出.99).

print_int_array((int[]){1, 1, 2, 3, 5}, 5);  
Run Code Online (Sandbox Code Playgroud)

99)请注意,这与演员表达不同.例如,强制转换指定转换为标量类型或void仅转换,并且转换表达式的结果不是左值.