Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Counting the elements in an array (C++)
    So I'm trying to do a function that takes in an array and checks if the elements in it are in a geometric sequence. Before I could do this function I need to know the number of elements in the array, witch I did like this: string ArithGeo(int arr[]) { int i = 0; while(arr[i]) { cout << arr[i] << " "; i++; } return ""; } But it looks like this code only works when the array has an odd number of elements, when the array has an even number of elements the while loop does another cycle even though arr[i] does not exist... Can anyone help me figure out the proper way to do it?
    MrJames posted this question on 4/22/14 | array, cpp
  • +
  • 4
  • -
  • What you are trying to do is not going to work. You should not invoke sizeof on the argument of the function, because the argument is not truly an array, but merely a pointer to its beginning (64-bit = 8 bytes). The first element is an int (32 = 4 bytes) in your case. You can read about the reason why arrays decay to pointer in function calls in any solid c or c++ book. Those two sizes are platform-dependent btw. What you need to do to get the size is to change the function interface to take a second parameter for the size. Then, in addition to that, invoke sizeof on the array in the main() function to determine the parameter and pass it to your function. You should have something like this: type A[] = gets(stdin); size_t size = sizeof(A)/sizeof(A[0]); As an alternative construct a vector or an other more advanced data type in main().
  • +
  • 3
  • -
  • If you're working with a Standard Library array (rarely a bad idea), you can simply call the size method: #include <array> using namespace std; array<int, 10> i_arr; cout << "i_arr size: " << i_arr.size() << endl; But if you're working with a normal C array, you can just do: int a[10]; size_t S = sizeof(a)/sizeof(a[0]); That should do ya.
  • +
  • 0
  • -
  • I tried the seccond method you showed (because when I try to # include <array>, it has compiler errors because it is not C++11...) and it works when I have an array initialised right befor taking the sizeof(array), but if I set it up like this: string ArithGeo(int arr[]) { cout << sizeof(arr); //always displays 8 cout << sizeof(arr[0]); //always displays 4 return ""; } It doesn't work, and sizeof(arr) returns 8, even if it has more than two elements...
    Log in to write an answer.