regarding array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cath8024
    New Member
    • Apr 2007
    • 7

    regarding array

    [code=c]#include<stdio. h>
    int arr[] = {1, 2, 3, 4, 5};
    #define NUMBER_OF_ELEME NTS (sizeof(arr) / sizeof(arr[0]))
    int main()
    {
    int index = -1;
    if (index <= NUMBER_OF_ELEME NTS - 3)
    printf( "A problem is not a problem if it CAN be solved\n"
    "A problem is not a problem if it CANNOT be solved\n");
    else
    printf("Time stays long enough for anyone who will use it\n");
    return 0;
    }[/code]


    can anyone give the explanation to why is the output "Time stays long enough for anyone who will use it."
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    Moving this to the C++/C forum.

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      My guess is that, in your define statement, sizeof(arr) is not giving you the results you are expecting. It is probably calculating the size of the pointer, not the array. This means you are dividing a small value by a larger value (since an integer takes up more memory than a pointer) and getting 0.

      Comment

      • AdrianH
        Recognized Expert Top Contributor
        • Feb 2007
        • 1251

        #4
        Originally posted by Ganon11
        My guess is that, in your define statement, sizeof(arr) is not giving you the results you are expecting. It is probably calculating the size of the pointer, not the array. This means you are dividing a small value by a larger value (since an integer takes up more memory than a pointer) and getting 0.
        No, it is doing it correctly. Turn on the warnings of your compiler. You will see a comparison warning.


        Adrian

        Comment

        Working...