在静态数组和动态数组元素的数量 [英] Number of elements in static array and dynamic array

查看:111
本文介绍了在静态数组和动态数组元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the quickest way to find the number of elements in a static array and dynamic array?

推荐答案

有没有发现在动态创建的数组元素的数量的方法。对于非动态数组,你可以使用的sizeof(阵列)/的sizeof(类型)。但是,因为它似乎这是不是有用:

There is no way of finding the number of elements in a dynamically created array. For a non-dynamic array, you can use sizeof(array)/sizeof(type). However, this is not as useful as it seems:

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

这是因为数组衰变为指针传递给函数的时候。因此,在这两种情况下,则可能需要记住阵列的大小并将它传递给功能作为单独的参数。因此,在函数总结数组(例如)应该是这样的:

This is because arrays decay into pointers when passed to functions. So in both cases, you probably need to remember the size of the array and pass it to functions as a separate parameter. So a function to sum an array (for example) would look like this:

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

这篇关于在静态数组和动态数组元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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