在功能使用数组 - Ç [英] Using array in function - C
本文介绍了在功能使用数组 - Ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
#include <iostream>
using namespace std;
int write(int arr[])
{
int n = (sizeof(arr)/sizeof(arr[0]));
for(int r=0;r<n;r++)
{
printf("%d\n", arr[r]);
}
return 0;
}
int main()
{
int numlist[] = {1, 3, 5, 6, 7, 9, 0, 2, 3};
write(numlist);
std::string strvar;
std::cin >> strvar;
}
什么是被印在屏幕上只是数字1。而已。
刚开始C和我只是试图让语法的窍门。
What is being printed on the screen is just the number '1'. Nothing more. Just beginning C and I'm only trying to get the hang of the syntax.
推荐答案
您不能计算数组的大小的 的内部使用功能
You cannot compute the size of the array inside the function using
(sizeof(arr)/sizeof(arr[0]));
这是因为该功能只看到改编
作为指针(数组衰变成一个指针),而不是作为一个完整的数组。因此, N
将 1
。
That is because the function only sees arr
as a pointer (the array decayed into a pointer), not as a full array. Thus, n
will be 1
.
您必须将大小作为传递一个额外的参数。
You have to pass the size as an extra argument.
int write(int arr[], int n)
{
for(int r=0;r<n;r++)
printf("%d\n", arr[r]);
return 0;
}
和与调用它
write(numlist, sizeof(arr)/sizeof(arr[0]));
这篇关于在功能使用数组 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文