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

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

问题描述

在下面的程序中,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.

推荐答案

没有内置"方式来确定函数内部的长度.不管你如何传递 arrsizeof(arr) 都会返回指针大小.所以最好的方法是将元素的数量作为单独的参数传递.或者你可以有一个特殊的值,如 0-1 表示结束(就像它是字符串中的 \0 ,它只是 <代码>字符[]).但是当然逻辑"数组大小是 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天全站免登陆