有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。


当前回答

你可以通过以下方法找到数组的长度:

int  arr[] = {1, 2, 3, 4, 5, 6}; 
int size = *(&arr + 1) - arr; 
cout << "Number of elements in arr[] is "<< size; 
return 0;

其他回答

你可以简单地使用这段代码:

#include <iostream>
#include <string>
#include <array>

using namespace std;

int main()
{

  array<int,3> values;
  cout << "No. elements in valuea array: " << values.size() << " elements." << endl;
  cout << "sizeof(myints): " << sizeof(values) << endl;

}

这里是参考资料:http://www.cplusplus.com/reference/array/array/size/

你有很多选项可以用来获取C数组的大小。

int myArray[] = {0, 1, 2, 3, 4, 5, 7};

1) sizeof(<array>) / sizeof(<type>):

std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;

2) sizeof(<array>) / sizeof(*<array>):

std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;

3) sizeof(<数组>)/ sizeof(<数组>[<元素>]):

std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;

我认为这是可行的:

for(int i=0;array[i];i++)
{
 //do_something
}  

我在这里提供了一个棘手的解决方案:

你总是可以在第一个元素中存储长度:

// malloc/new

arr[0] = length;
arr++;

// do anything. 
int len = *(arr-1);

free(--arr); 

代价是在调用free时必须—arr

还有TR1/ c++ 11/ c++ 17方式(参见Coliru Live):

const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n       = std::extent<   decltype(s) >::value; // From <type_traits>
constexpr auto n2      = std::extent_v< decltype(s) >;        // C++17 shorthand

const auto     a    = std::array{ "1"s, "2"s, "3"s };   // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
constexpr auto size = std::tuple_size_v< decltype(a) >;

std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3