Array length counting anomaly

后端 未结 4 703
挽巷
挽巷 2021-01-26 05:17

The count is returning unpredictable results. Sometimes they are right. Sometimes totally weird. Anyone can tell me what is wrong?

#include 
int l         


        
4条回答
  •  [愿得一人]
    2021-01-26 05:33

    I think you're confused between C strings (arrays of char) and other arrays. It's a convention that C strings are terminated with a null character ('\0'), but not all arrays (even char arrays) are terminated this way.

    The general convention is to either store the length of an array somewhere, or to use a sentinel value at the end of the array. This value should be one that won't come up inside the array - eg '\0' in strings, or -1 in an array of positive ints.

    Also, if you know that a is an int array (and not a pointer to an int array), then you can use:

    size_t length = sizeof(a) / sizeof(a[0]);
    

    So you could do:

    int a[] = {1,2,3,4,5,6,7,8};
    size_t length = sizeof(a) / sizeof(a[0]); 
    
    // In this case, sizeof(a[0]) 
    // is the same as sizeof(int), because it's an int array.
    

    But you can't do:

    int *a = malloc(sizeof(int) * 10);
    size_t length = sizeof(a) / sizeof(a[0]); // WRONG! 
    

    That last example will compile, but the answer will be wrong, because you're getting the size of a pointer to the array rather than the size of the array.

    Note that you also can't use this sizeof to read the size of an array that's been passed into a function. It doesn't matter whether you declare your function len(int *a) or len(int a[]) - a will be a pointer, because the compiler converts arrays in function arguments to be a pointer to their first element.

提交回复
热议问题