找回密码
 快速注册
搜索
查看: 33|回复: 1

Passing an array as an argument to a function in C

[复制链接]

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

hbghlyj 发表于 2022-8-29 20:03 |阅读模式
W3School讲得很浅:C++ Pass Array to a Function,只说了如何将数组传给函数.
比如要计算整型的数组l1的长度,
  1. #include<stdio.h>
  2. int main() {
  3.     int l1[] = { 9, 9, 9, 9, 9, 9, 9 };
  4.     printf("%d", (int)(sizeof(l1) / sizeof(int)));
  5.     return 0;
  6. }
复制代码

打印结果为 7, 是所预期的. 但如果做成一个“以数组为参数”的函数:
  1. #include<stdio.h>
  2. void func(int l1[]) {
  3.     printf("%d", (int)(sizeof(l1) / sizeof(int)));
  4. }
  5. int main() {
  6.     int l1[] = { 9, 9, 9, 9, 9, 9, 9 };
  7.     func(l1);
  8.     return 0;
  9. }
复制代码

打印结果却是 2. 这是因为sizeof(l1)是计算“指针类型int*的size”, (在CPU architecture是x64情况下)是8字节, 所以是int的size的两倍. 而且gcc会发出警告:
'sizeof' on array function parameter 'l1' will return size of 'int *' [-Wsizeof-array-argument] Screenshot 2022-08-29 at 03-53-21 pgfmanual.pdf.png

又见stackoverflow.com/questions/6567742
When passing an array as a parameter, this
void arraytest(int a[])
means exactly the same as
void arraytest(int *a)
For historical reasons, arrays are not first class citizens and cannot be passed by value.

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

 楼主| hbghlyj 发表于 2022-8-29 20:21
无法写出“输入数组int l1[]并输出它的大小”的函数, 因为比如说void func(int l1[]), 这里的l1实际上是l1[0]的指针. 那么这个func只知道数组的一个元素的地址, 无法得知数组的大小.

手机版|悠闲数学娱乐论坛(第3版)

GMT+8, 2025-3-4 15:53

Powered by Discuz!

× 快速回复 返回顶部 返回列表