是否可以在C中使用匿名的即席数组? [英] Is it possible to have anonymous, ad-hoc arrays in C?

查看:76
本文介绍了是否可以在C中使用匿名的即席数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在C中创建匿名的即席数组?

Is it possible to create anonymous, ad-hoc arrays in C?

例如,假设我有一个名为processArray(int[] array)的函数,该函数将int数组作为其参数,我可以通过以下方式将其传递给匿名数组:

For example, suppose I have a function called processArray(int[] array) that takes an int array as its argument, can I pass it an anonymous array in the following way:

int main(){
 processArray( (int[]){0, 1, 2, 3} ); //can I create this type of array?
 return 0;
}

还是我必须事先声明数组(使用指针),然后将其指针传递给processArray()?例如:

Or do I have to declare the array previously (with a pointer), and then pass its pointer to processArray()? For example:

int main(){
 int[] myArray = {0, 1, 2, 3};
 processArray(myArray);
 return 0;
}

推荐答案

使用C99和C11,您可以编写自己编写的内容,如以下代码所示.这些是复合文字",在ISO/IEC 9899:2011 § 6.5.2.5复合文字(与ISO/IEC 9899:1999中的该部分相同).

With C99 and C11, you can write what you wrote, as exemplified by the following code. These are 'compound literals', described in ISO/IEC 9899:2011 §6.5.2.5 Compound literals (and it is the same section in ISO/IEC 9899:1999).

#include <stdio.h>

static void processArray(int n, int arr[])
{
    for (int i = 0; i < n; i++)
       printf(" %d", arr[i]);
    putchar('\n');
}

int main(void)
{
    processArray(4, (int[]){0, 1, 2, 3});
    return 0;
}

运行时,它会产生答案:

When run, it produces the answer:

 0 1 2 3

这篇关于是否可以在C中使用匿名的即席数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆