我可以使用数组作为C99函数参数? [英] Can I use arrays as a function parameter in C99?

查看:130
本文介绍了我可以使用数组作为C99函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C99标准说,在6.7.5.3/7以下内容:

The C99 standard says the following in 6.7.5.3/7:

一个参数为''类型的数组'的声明应调整到'合格的指针
             类型'',其中类型限定符(如果有的话)的那些内的的[和]指定
                数组类型推导。

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.

我的理解是:

void foo(int * arr) {} // valid
void foo(int arr[]) {} // invalid

不过,GCC 4.7.3会很乐意接受这两个函数定义,即使与 GCC编译-Wall -std -Werror C99 = -pedantic-错误。由于我不是一个C的专家,我不能确定,如果可能我misinter preTED什么标准说。

However, gcc 4.7.3 will happily accept both function definitions, even when compiled with gcc -Wall -Werror -std=c99 -pedantic-errors. Since I am not a C expert, I am unsure if maybe I misinterpreted what the standard is saying.

我也注意到,

size_t foo(int arr[]) { return sizeof(arr); }

总是返回的sizeof(INT *)而不是数组大小,这公司我相信 INT ARR [] 为int * 和gcc只是试图让我感觉更舒服处理。

will always return sizeof(int *) instead of the array size, which firms my belief that int arr[] is handled as int * and gcc is just trying to make me feel more comfortable.

有人可以阐明这个问题一些轻?仅供参考,这个问题从<一起来href=\"http://stackoverflow.com/questions/18829274/how-to-call-a-function-with-a-reference-to-an-unknown-size-array/#comment27782308_18829776\">this评论。

Can someone shed some light on this issue? Just for reference, this question arose from this comment.

推荐答案

这两个您的有效的和的无效的声明是在内部相同,即,编译器将后者以前者。

Both your valid and invalid declarations are internally equivalent, i.e., the compiler converts the latter to the former.

你的函数看到的是指向数组的第一个元素。

What your function sees is the pointer to the first element of the array.

PS。另一种方法是推的整个阵列堆栈,这将是从时间和空间上的观点非常低效的

PS. The alternative would be to push the whole array on the stack, which would be grossly inefficient from both time and space viewpoints.

这篇关于我可以使用数组作为C99函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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