使用函数计算 C 中数组的长度 [英] Calculate Length of Array in C by Using Function

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

问题描述

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

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);

}

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

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

我试过了:

int ArraySize(int * Array)
{

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

}

这不会起作用,因为sizeof(Array)"将重新调整 Int 指针的大小.这个sizeof"只有当你在同一个函数中时才有效.

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

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

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

问候!

推荐答案

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

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.

(下面的评论确实属于答案......)

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

  1. 无法确定数组中初始化的元素数量,除非您首先将所有元素初始化为无效"值并计算有效"值手动.如果你的数组被定义为有 8 个元素,那么对于编译器来说,它有 8 个元素,不管你是否只初始化了其中的 5 个.
  2. 无法确定该数组作为参数传递给的函数内的数组大小.不是直接的,不是通过宏,不是以任何方式.您可以确定数组的大小在其声明的范围内.
  1. You cannot determine the number of elements initialized within 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 cannot determine 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 only determine the size of an array in the scope it has been declared in.

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

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

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

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

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

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 different arrays, and remember that sizeof() is a compile-time operator.

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

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

#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;
}

底线:C 数组是有限的.您不能在子函数期间计算它们的长度.您必须以自己的方式绕过该限制,或者使用不同的语言(如 C++).

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 中数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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