静态数组和动态数组中的元素数

时间:2010-04-05 09:36:43

标签: c arrays

找到静态数组和动态数组中元素数量的最快方法是什么?

1 个答案:

答案 0 :(得分:10)

无法找到动态创建的数组中的元素数量。对于非动态数组,您可以使用sizeof(array)/sizeof(type)。但是,这并不像看起来那么有用:

void f( int a[] ) {
   // sizeof(a) will be the size of a pointer, probably 4
}

int main() {
     int a[100];
     // sizeof(a)/sizeof(int) will be 100
     f( a );
}

这是因为数组在传递给函数时会衰减为指针。因此,在这两种情况下,您可能需要记住数组的大小并将其作为单独的参数传递给函数。因此,对数组求和的函数(例如)将如下所示:

int sum( int a[], int n ) {
    int total = 0, i;    
    for ( i = 0; i < n; i++ ) {
        total += a[i];
    }
    return total;
}
相关问题