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


当前回答

只是一个想法,但只是决定创建一个计数器变量,并将数组大小存储在位置[0]。我删除了函数中的大部分代码,但你会看到退出循环后,prime[0]被分配为'a'的最终值。我尝试使用矢量,但VS Express 2013不太喜欢。还要注意,'a'从1开始,以避免覆盖[0],并在开始时初始化以避免错误。我不是专家,只是想分享一下。

int prime[] = {0};
int primes(int x, int y){
    using namespace std; int a = 1;
    for (int i = x; i <= y; i++){prime[a] = i; a++; }
    prime[0] = a; return 0;
}

其他回答

如果你指的是c风格的数组,那么你可以这样做:

int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;

这对指针不起作用(即它对以下任何一个都不起作用):

int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;

or:

void func(int *p)
{
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}

int a[7];
func(a);

在c++中,如果你想要这种行为,那么你应该使用容器类;可能std::向量。

下面是谷歌Protobuf中ArraySize的一个实现。

#define GOOGLE_ARRAYSIZE(a) \
  ((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;

ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling. Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t. This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.

你有很多选项可以用来获取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;

而不是使用内置的数组函数aka:

 int x[3] = {0, 1, 2};

您应该使用数组类和数组模板。试一试:

#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};

现在如果你想求数组的长度,你所要做的就是使用数组类中的size函数。

Name_of_Array.size();

这应该返回数组中元素的长度。

避免将类型与sizeof一起使用,因为如果改变数组类型,sizeof(array)/sizeof(char)会突然被破坏。

在visual studio中,你有等效的if sizeof(array)/sizeof(*array)。 你可以输入_countof(array)