检查数组的长度[重复](Checking length of array [duplicate])

编程入门 行业动态 更新时间:2024-10-17 02:56:23
检查数组的长度[重复](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).

更多推荐

本文发布于:2023-08-07 12:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   长度   Checking   duplicate   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!