How do I find the length of an array?

前端 未结 27 3319
轮回少年
轮回少年 2020-11-21 23:10

Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.

27条回答
  •  耶瑟儿~
    2020-11-21 23:10

    Just a thought, but just decided to create a counter variable and store the array size in position [0]. I deleted most of the code I had in the function but you'll see after exiting the loop, prime[0] is assigned the final value of 'a'. I tried using vectors but VS Express 2013 didn't like that very much. Also make note that 'a' starts at one to avoid overwriting [0] and it's initialized in the beginning to avoid errors. I'm no expert, just thought I'd share.

    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;
    }
    

提交回复
热议问题