Forgot password?
 Create new account
View 114|Reply 1

Passing an array as an argument to a function in C

[Copy link]

3147

Threads

8493

Posts

610K

Credits

Credits
66163
QQ

Show all posts

hbghlyj Posted at 2022-8-29 20:03:25 |Read mode
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. }
Copy the Code

打印结果为 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. }
Copy the Code

打印结果却是 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.

3147

Threads

8493

Posts

610K

Credits

Credits
66163
QQ

Show all posts

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

手机版Mobile version|Leisure Math Forum

2025-4-20 22:27 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list