int数组的大小发现 [英] finding size of int array
问题描述
如何找到一个int数组的大小?例如:
How to find size of an int array? eg:
int list[]={1,5,7,8,1,1,4,5,7,7,7,8,10,20};
如何列表的大小?
how to the size of list?
我知道字符数组。我们可以使用的strlen(阵列)
来找到的大小,或检查'\\ 0'
在的结束数组。
I know for char array. We can use strlen(array)
to find the size, or check with '\0'
at the end of the array.
但对于int数组,检查'\\ 0'
似乎不工作。
But for int array, checking '\0'
seems not working.
问题!!!!!!!!!! 的sizeof(阵列)/的sizeof(数组[0])
只能在主?如果我用它的一个函数里。例如:
Problem!!!!!!!!!! sizeof(array)/sizeof(array[0])
only works in main??? If i use it inside a function. eg:
#include <iostream>
using namespace std;
void size(int arr1[]){
int size;
size=sizeof(arr1)/sizeof(arr1[0]);
cout<<size<<endl;
}
int main(){
int list_1[]={1,5,7,8,1,1,4,5,7,7,7,8,10,20};
size(list_1);
return 0;
}
它不能打印正确的大小??
It can not print the right size??
推荐答案
试试这个:
sizeof(list)/sizeof(list[0]);
由于这个问题被标记C ++,它总是推荐使用的std ::矢量
在C ++中,而不是使用传统的C风格的数组。
Because this question is tagged C++, it is always recommended to use std::vector
in C++ rather than using conventional C-style arrays.
编辑:(因为这个问题已被编辑)
EDIT : (because the question has been edited)
这是数组类型
被隐式转换成指针式
当你把它传递给一个函数。
看一看<一个href=\"http://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language/1975133#1975133\">this.
An array-type
is implicitly converted into a pointer-type
when you pass it to a function.
Have a look at this.
为了正确打印sizeof的任何函数中的数组,通过引用数组传递给函数(但你需要事先知道数组的大小)
In order to correctly print the sizeof an array inside any function, pass the array by reference to that function(but you need to know the size of that array in advance)
编辑2 :亚当想知道如何通过引用传递数组
EDIT 2 : Adam wants to know how to pass the array by reference
#include <iostream>
template<typename T,int N>
//template argument deduction
void size(T (&arr1)[N]) //Passing the array by reference
{
size_t size;
size=sizeof(arr1)/sizeof(arr1[0]);
std::cout<<size<<std::endl; //Correctly prints the size of arr
//EDIT
std::cout<<N; //Correctly prints the size too [cool trick ;-)]
}
int main()
{
int list_1[]={1,5,7,8,1,1,4,5,7,7,7,8,10,20};
size(list_1);
return 0;
}
这篇关于int数组的大小发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!