我有
int list[] = {1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
如何获得大小list?
我知道对于char数组,我们可以strlen(array)用来查找大小,或者'\0'在数组末尾检查.
我尝试sizeof(array) / sizeof(array[0])了一些答案,但它只适用于主?例如:
int size(int arr1[]){
return sizeof(arr1) / sizeof(arr1[0]);
}
int main() {
int list[] = {1, 2, 3};
int size1 = sizeof(list) / sizeof(list[0]); // ok
int size2 = size(list_1); // no
// size1 and size2 are not the same
}
Run Code Online (Sandbox Code Playgroud)
为什么?
只是想写一个基本sum()功能.
int sum(int arr[]) {
int total = 0 , i = 0 , l = sizeof arr;
for(i=0;i<l;i++) {
total += arr[i];
}
return total;
}
Run Code Online (Sandbox Code Playgroud)
l总是等于4(我知道最终除以sizeof int)
在Windows 7中使用默认编译器选项运行Dev-C++.