C语言 使用函数计算 C 中数组的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4162923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:01:26  来源:igfitidea点击:

Calculate Length of Array in C by Using Function

carrays

提问by Swanand

I want to make a FUNCTION which calculates size of passed array.

我想做一个计算传递数组大小的函数。

I will pass an Array as input and it should return its length. I want a Function

我将传递一个数组作为输入,它应该返回它的长度。我想要一个函数

int ArraySize(int * Array   /* Or int Array[] */)
{
   /* Calculate Length of Array and Return it */

}

void main()
{
  int MyArray[8]={1,2,3,0,5};
  int length;

  length=ArraySize(MyArray);

  printf("Size of Array: %d",length);

}

Length should be 5 as it contains 5 elements though it's size is 8 (Even 8 will do but 5 would be excellent)

长度应该是 5,因为它包含 5 个元素,尽管它的大小是 8(即使是 8 也可以,但 5 会很好)

I tried this:

我试过这个:

int ArraySize(int * Array)
{

  return (sizeof(Array)/sizeof(int));

}

This won't work as "sizeof(Array)" will retun size of Int Pointer. This "sizeof" thing works only if you are in same function.

这将不起作用,因为“ sizeof(Array)”将重新调整 Int 指针的大小。sizeof只有当您处于相同的功能时,这个“ ” 东西才有效。

Actually I am back to C after lots of days from C# So I can't remember (and Missing Array.Length())

实际上,在使用 C# 很多天之后我又回到了 C,所以我不记得(和缺失Array.Length()

Regards!

问候!

回答by DevSolar

You cannot calculate the size of an array when all you've got is a pointer.

当您只有一个指针时,您无法计算数组的大小。

The only way to make this "function-like" is to define a macro:

使这种“类似函数”的唯一方法是定义一个宏:

#define ARRAY_SIZE( array ) ( sizeof( array ) / sizeof( array[0] ) )

This comes with all the usual caveats of macros, of course.

当然,这带有宏的所有常见警告。

Edit:(The comments below really belong into the answer...)

编辑:(下面的评论真的属于答案......)

  1. You cannotdetermine the number of elements initializedwithin an array, unless you initialize all elements to an "invalid" value first and doing the counting of "valid" values manually. If your array has been defined as having 8 elements, for the compiler it has 8 elements, no matter whether you initialized only 5 of them.
  2. You cannotdetermine the size of an array within a function to which that array has been passed as parameter. Not directly, not through a macro, not in any way. You can onlydetermine the size of an array in the scope it has been declared in.
  1. 无法确定数组中初始化的元素数量,除非您首先将所有元素初始化为“无效”值并手动计算“有效”值。如果你的数组被定义为有 8 个元素,那么对于编译器来说,它有 8 个元素,无论你是否只初始化了其中的 5 个。
  2. 无法在该数组作为参数传递给的函数中确定该数组的大小。不是直接的,不是通过宏,不是以任何方式。您只能确定数组在 中声明的范围内的大小。

The impossibility of determining the size of the array in a called function can be understood once you realize that sizeof()is a compile-timeoperator. It might looklike a run-time function call, but it isn't: The compilerdetermines the size of the operands, and inserts them as constants.

一旦您意识到它sizeof()是一个编译时运算符,就可以理解无法在被调用函数中确定数组的大小。它可能看起来像一个运行时函数调用,但它不是:编译器确定操作数的大小,并将它们作为常量插入。

In the scope the array is declared, the compiler has the information that it is actually an array, and how many elements it has.

在声明数组的作用域中,编译器知道它实际上是一个数组,以及它有多少元素。

In a function to which the array is passed, all the compiler sees is a pointer. (Consider that the function might be called with many differentarrays, and remember that sizeof()is a compile-time operator.

在传递数组的函数中,编译器看到的只是一个指针。(考虑到可能会使用许多不同的数组调用该函数,请记住这sizeof()是一个编译时操作符

You can switch to C++ and use <vector>. You can define a struct vectorplus functions handling that, but it's not really comfortable:

您可以切换到 C++ 并使用<vector>. 您可以定义一个struct vector加号函数来处理它,但它不是很舒服:

#include <stdlib.h>

typedef struct
{
    int *  _data;
    size_t _size;
} int_vector;

int_vector * create_int_vector( size_t size )
{
    int_vector * _vec = malloc( sizeof( int_vector ) );
    if ( _vec != NULL )
    {
        _vec._size = size;
        _vec._data = (int *)malloc( size * sizeof( int ) );
    }
    return _vec;
}

void destroy_int_vector( int_vector * _vec )
{
    free( _vec->_data );
    free( _vec );
}

int main()
{
    int_vector * myVector = create_int_vector( 8 );
    if ( myVector != NULL && myVector->_data != NULL )
    {
        myVector->_data[0] = ...;
        destroy_int_vector( myVector );
    }
    else if ( myVector != NULL )
    {
        free( myVector );
    }
    return 0;
}

Bottom line: C arrays are limited. You cannot calculate their length in a sub-function, period. You have to code your way around that limitation, or use a different language (like C++).

底线:C 数组是有限的。您不能在子函数期间计算它们的长度。您必须围绕该限制编写代码,或使用不同的语言(如 C++)。

回答by paxdiablo

You can't do this once the array has decayed to a pointer - you'll always get the pointer size.

一旦数组衰减为指针,您就无法执行此操作 - 您将始终获得指针大小。

What you need to do is either:

您需要做的是:

  • use a sentinel value if possible, like NULL for pointers or -1 for positive numbers.
  • calculate it when it's still an array, and pass that size to any functions.
  • same as above but using funky macro magic, something like:
    #define arrSz(a) (sizeof(a)/sizeof(*a)).
  • create your own abstract data type which maintains the length as an item in a structure, so that you havea way of getting your Array.length().
  • 如果可能,请使用标记值,例如 NULL 表示指针或 -1 表示正数。
  • 当它仍然是一个数组时计算它,并将该大小传递给任何函数。
  • 与上面相同,但使用时髦的宏观魔法,是这样的:
    #define arrSz(a) (sizeof(a)/sizeof(*a))
  • 创建您自己的抽象数据类型,将长度作为结构中的一个项目进行维护,以便您可以通过某种方式获取Array.length().

回答by JeremyP

What you ask for simply can't be done.

你所要求的根本无法完成。

At run time, the only information made available to the program about an array is the address of its first element. Even the size of the elements is only inferred from the type context in which the array is used.

在运行时,程序可用的有关数组的唯一信息是其第一个元素的地址。甚至元素的大小也只能从使用数组的类型上下文中推断出来。

回答by Mayuresh Sawant

int getArraySize(void *x)
{
    char *p = (char *)x;
    char i = 0;
    char dynamic_char = 0xfd;
    char static_char = 0xcc;

    while(1)
    {
        if(p[i]==dynamic_char || p[i]==static_char)
            break;
        i++;
    }
    return i;
}

int _tmain(int argc, _TCHAR* argv[])
{   
    void *ptr = NULL;
    int array[]={1,2,3,4,5,6,7,8,9,0};
    char *str;
    int totalBytes;

    ptr = (char *)malloc(sizeof(int)*3);
    str = (char *)malloc(10);

    totalBytes = getArraySize(ptr);
    printf("ptr = total bytes = %d and allocated count = %d\n",totalBytes,(totalBytes/sizeof(int)));

    totalBytes = getArraySize(array);
    printf("array = total bytes = %d and allocated count = %d\n",totalBytes,(totalBytes/sizeof(int)));

    totalBytes = getArraySize(str);
    printf("str = total bytes = %d and allocated count = %d\n",totalBytes,(totalBytes/sizeof(char)));
    return 0;
}

回答by Prasoon Saurav

In C you can't because array decays into a pointer(to the first element) when passed to a function.

在 C 中你不能因为数组在传递给函数时衰减为指针(指向第一个元素)。

However in C++ you can use Template Argument Deductionto achieve the same.

但是在 C++ 中,您可以使用模板参数推导来实现相同的目的。

回答by Blindy

You need to either pass the length as an additional parameter (like strncpydoes) or zero-terminate the array (like strcpydoes).

您需要将长度作为附加参数传递(如strncpydo)或以零终止数组(如strcpydo)。

Small variations of these techniques exist, like bundling the length with the pointer in its own class, or using a different marker for the length of the array, but these are basically your only choices.

这些技术存在一些小的变化,例如将长度与指针捆绑在其自己的类中,或者使用不同的标记来表示数组的长度,但这些基本上是您唯一的选择。

回答by nakul parashar

Is is very late. But I found a workaround for this problem. I know it is not the proper solution but can work if you don't want to traverse a whole array of integers.

是很晚了。但是我找到了解决此问题的方法。我知道这不是正确的解决方案,但如果您不想遍历整个整数数组,它可以工作。

checking '\0' will not work here

检查 '\0' 在这里不起作用

First, put any character in array at the time of initialization

首先,在初始化时将任何字符放入数组

for(i=0;i<1000;i++)
array[i]='x';

then after passing values check for 'x'

然后在传递值后检查 'x'

i=0;
while(array[i]!='x')
{
i++;
return i;
}

let me know if it is of any use.

让我知道它是否有任何用处。

回答by Ajay Kumar

Not possible. You need to pass the size of the array from the function, you're calling this function from. When you pass the array to the function, only the starting address is passed not the whole size and when you calculate the size of the array, Compiler doesn't know How much size/memory, this pointer has been allocated by the compiler. So, final call is, you need to pass the array size while you're calling that function.

不可能。您需要从函数传递数组的大小,您正在调用此函数。当您将数组传递给函数时,只传递起始地址而不是整个大小,当您计算数组的大小时,编译器不知道有多少大小/内存,这个指针已被编译器分配。因此,最终调用是,您需要在调用该函数时传递数组大小。

回答by Md Shahriar

Size of an arry in C is :

C 中 arry 的大小是:

int a[]={10,2,22,31,1,2,44,21,5,8};

printf("Size : %d",sizeof(a)/sizeof(int));