-1

I want to get an array length, I try to use by function, But in the function, I get array length is worry, the operation result is 2, Who can help me do this.

#include <stdio.h>
#define GET_ARRAY_LEN(array,len){len = (sizeof(array) / sizeof(array[0]));}

void print_arry(int *nums){
        int i;
        int len;

        GET_ARRAY_LEN(nums, len);
        printf("%d\n",len);

        for (i=0; i<len; i++)
                printf ("%d ", nums[i]);
}

int main() {
        int nums[]={ 2,7,3,11,15 };
        int target = 9;

        print_arry(nums);
        return 0;
}

But this is right, I don't where it is wrong.

#include <stdio.h>

#define GET_ARRAY_LEN(array,len){len = (sizeof(array) / sizeof(array[0]));}


int main() {
        int nums[]={ 2,7,3,11,15 };
        int target = 9;
        int len;

        GET_ARRAY_LEN(nums, len);
        printf("%d\n",len);

        return 0;
}
Little
  • 7
  • 1

1 Answers1

2

When you pass an array to a function (or use it in a myriad of other ways), it decays into a pointer to the first element of that array(a).

That means it will be a pointer, with the size of a pointer, not the size of the original array.

If you want to know the size, you'll have to work that out while it's still an array and pass that as well, something like:

void print_arry (int *nums, size_t sz) {
    printf ("%z:", sz);
    for (size_t i = 0; i < sz; ++i) {
        printf (" %d", nums[i]);
    }
    putchar ('\n');
}
:
print_arry (nums, sizeof(nums) / sizeof(*nums));

(a) See, for example, C11 6.3.2.1 Lvalues, arrays, and function designators /3:

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953