检查数组的长度[重复](Checking length of array [duplicate])
这个问题在这里已有答案:
查找函数内部数组的长度 8答案 #define lengthOfArray(x) (sizeof(x) / sizeof(x[0]))似乎在main()中给出了正确的答案,但是在array_set()的printf()中。 我错过了什么?
int* decValue2[BUF_SIZE] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; #define lengthOfArray(x) (sizeof(x) / sizeof(x[0])) void array_set(int* y_dest, int* y_src, int arrayLength){ // arrays int i = 0; printf("lengthOfArray in function: %d \n", lengthOfArray(y_src)); // [TODO] check that y_dest has enough space for (i=0;i<arrayLength; i++) y_dest[i] = y_src[i]; // } // In main() int y_int = 0; int y_array[BUF_SIZE]; int_set_right( &y_int, 9876543); array_set(y_array, decValue2, BUF_SIZE); printf("lengthOfArray: %d \n", lengthOfArray(y_array)); printf("Value int :: %d \n",y_int); int i = 0; for (i=0;i<BUF_SIZE; i++) printf("%x ", (0xff & y_array[i]));This question already has an answer here:
Finding length of array inside a function [duplicate] 8 answers #define lengthOfArray(x) (sizeof(x) / sizeof(x[0]))seems to give the right answer in main(), but in the printf() of array_set(). Did I miss something?
int* decValue2[BUF_SIZE] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; #define lengthOfArray(x) (sizeof(x) / sizeof(x[0])) void array_set(int* y_dest, int* y_src, int arrayLength){ // arrays int i = 0; printf("lengthOfArray in function: %d \n", lengthOfArray(y_src)); // [TODO] check that y_dest has enough space for (i=0;i<arrayLength; i++) y_dest[i] = y_src[i]; // } // In main() int y_int = 0; int y_array[BUF_SIZE]; int_set_right( &y_int, 9876543); array_set(y_array, decValue2, BUF_SIZE); printf("lengthOfArray: %d \n", lengthOfArray(y_array)); printf("Value int :: %d \n",y_int); int i = 0; for (i=0;i<BUF_SIZE; i++) printf("%x ", (0xff & y_array[i]));最满意答案
lengthOfArray对指针(与数组相对)不能正常工作,因为sizeof(x)将返回指针的大小而不是指向数组的大小。
你必须明确地将数组的大小传递给函数(就像你已经做的那样)。
lengthOfArray won't work correctly for pointers (as opposed to arrays), since sizeof(x) will return the size of the pointer and not the size of the pointed-to array.
You have to explicitly pass the size of the array into the function (as you already do).
更多推荐
发布评论