If the array is a global, static, or automatic variable (int array[10];
), then sizeof(array)/sizeof(array[0])
works.
If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);
) or passed as a function argument (void f(int array[])
), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0])
compiles just fine even for the second case, but it will silently produce the wrong result.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…