Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • ArithGeo in C++
    Hi guys, I have a very short and simply question that troubles me quite a lot, I'm a beginner though! I use the following code to find the number of elements in my array(ie input). But when my input was {1,2,3,4,5} The result was 6. Why? Thx for helping.
    int arrSize =0;
    
    while(arr[arrSize])
        arrSize++;
    
    RavenTan posted this question on 1/14/14 | array, size, cpp
    Answers
  • +
  • 1
  • -
  • You can access elements in memory outside of arr length with operator [] as your code is valid at compilation time. However, this can produce lot of troubles at execution as you are accessing something you don't know. In your case, the next 4 bytes of memory are filled with something making arr[arrSize] returning true, so you end up with a wrong size. Note that this could end at any number or even crash the program. Basically, finding the number of elements in an array is equal to dividing the size of the array by the size of its elements. Something like :
    int arrSize = sizeof(arr)/sizeof(int)
    should do it (my c++ is rusty).
  • +
  • 0
  • -
  • Sentropie is right. That's why I love those languages, you have to know what you're doing :)
  • +
  • 0
  • -
  • Thanks for your advice but i tried, it doesn't work :( it keeps on returning 2 even if my array contains more than 2 elements... Anyone got any idea????
  • +
  • 0
  • -
  • I guess your problem is that you pass the array as a function parameter. You have to calculate it before passing it as a parameter and pass the array size as a second parameter. I think the C++ template for those kind of challenges should already suggest this but hey. (To correctly calculate the array size before passing, use tooNoob's code.)
    Log in to write an answer.