为什么要在函数标头中声明C数组参数的大小? [英] Why should I declare a C array parameter's size in a function header?

查看:168
本文介绍了为什么要在函数标头中声明C数组参数的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能启发我为什么要麻烦在函数头中指定C数组参数的大小吗?例如:

Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:

void foo (int iz[6]) { iz[42] = 43; }

使用:

int is[2] = {1,2,3};

我们收到一个有用的错误.也许对评论/文档有帮助吗?

we get a useful error. Perhaps it helps with commenting/documentation?

推荐答案

有人能启发我为什么要麻烦在函数头中指定C数组参数的大小吗?例如:

Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:

void foo(const char sz [6]){sz [42] = 43; }

void foo (const char sz[6]) { sz[42] = 43; }

海事组织,你不应该.当您尝试将数组传递给函数时,真正传递的是指向数组开头的指针.由于该函数接收到的将是一个指针,因此最好编写它使其明确:

IMO, you shouldn't. When you try to pass an array to a function, what's really passed is a pointer to the beginning of the array. Since what the function receives will be a pointer, it's better to write it to make that explicit:

void foo(char const *sz)

然后,由于现在很清楚该函数没有大小提示,因此请将其添加为单独的参数:

Then, since it's now clear that the function has been given no clue of the size, add that as a separate parameter:

void foo(char const *sz, size_t size)

这篇关于为什么要在函数标头中声明C数组参数的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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