功能参数与声明大小的数组 [英] Function parameter as array with declared size

查看:186
本文介绍了功能参数与声明大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用下列约定通知客户code,一个功能需要与定义大小的数组的参数:

I frequently use the following convention to inform client code that a function requires an argument of an array with defined size:

/* File foo.h */
int foo (int arg[10]);

我想给客户code的消息是,他们的必须提供类型 INT 数组与10个职位。

The message I want to give to client code is that they must provide an array of type int with 10 positions.

我知道,这不是很平常,所以我来这里问:我失去了本公约的任何副作用?它是无论如何有害吗?

I am aware that it is not very usual, so I came here to ask: Am I missing any side effect of this convention ? Is it anyhow harmful?

感谢!

推荐答案

如果你想坚持让大小为10的数组,你可以使用:

If you want to insist on getting an array of size 10, you can use:

int foo (int (*arg)[10]);

这样做的不良副作用是:

The ill-side effects of this are:


  1. 在功能,你必须使用:

  1. In the function, you have to use:

(*arg)[index] 

而不仅仅是

arg[index]


  • 调用函数必须使用:

  • The calling function must use:

    int array[10];
    foo(&array);
    

    而不是

    int array[10];
    foo(array);
    


  • 您不能使用已经超过10个元素的数组。

  • You cannot use an array that has more than 10 elements.

    int array[20];
    foo(&array);   // Not OK.
    


  • 您不能使用的malloc ED阵列。

    int* array = malloc(sizeof(int)*10);
    foo(array);   // Not OK.
    


  • 现在挑的解决方案,至少是有害的。

    Now pick the solution that is least harmful.

    这篇关于功能参数与声明大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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