在函数内部查找数组的长度 [英] Finding length of array inside a function

查看:73
本文介绍了在函数内部查找数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,数组ar的长度在main中是正确的,但在temp中则显示了指向ar的指针的长度,该指针在我的计算机上为2(以sizeof(int)为单位).

In the program below the length of the array ar is correct in main but in temp it shows the length of the pointer to ar which on my computer is 2 (in units of sizeof(int)).

#include <stdio.h>

void temp(int ar[]) // this could also be declared as `int *ar`
{
    printf("%d\n", (int) sizeof(ar)/sizeof(int));
}

int main(void)
{
    int ar[]={1,2,3};
    printf("%d\n", (int) sizeof(ar)/sizeof(int));
    temp(ar);
    return 0;
}

我想知道如何定义函数,以便在函数中正确读取数组的长度.

I wanted to know how I should define the function so the length of the array is read correctly in the function.

推荐答案

没有确定函数内部长度的内置"方法.但是,您传递arr时,sizeof(arr)将始终返回指针大小.因此,最好的方法是将元素数量作为单独的参数传递.另外,您可能有一个特殊的值,例如0-1,它指示结尾(就像字符串中的\0一样,只是char []). 但是,当然,逻辑"数组的大小当然是sizeof(arr)/sizeof(int) - 1

There is no 'built-in' way to determine the length inside the function. However you pass arr, sizeof(arr) will always return the pointer size. So the best way is to pass the number of elements as a seperate argument. Alternatively you could have a special value like 0 or -1 that indicates the end (like it is \0 in strings, which are just char []). But then of course the 'logical' array size was sizeof(arr)/sizeof(int) - 1

这篇关于在函数内部查找数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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