[英]size of array in C without sizeof and not in main function
I want to understand how to know the size of array without using sizeof and not in main function.我想了解如何在不使用 sizeof 而不是主要 function 的情况下知道数组的大小。 and i really want to understand why my code not working when i do it in other function.(in main it works same as sizeof).
我真的很想了解为什么我的代码在其他 function 中执行时不起作用。(主要它与 sizeof 相同)。 >>> The rasult i got are some trash numbers
>>> 我得到的结果是一些垃圾号码
*with char array is understood but i dont know how to do it with other data specifiers. * 使用 char 数组可以理解,但我不知道如何使用其他数据说明符。
#include <stdio.h>
void arrSize(int a[],int b[]){
int size_a = *(&a+1) - a;
int size_b = *(&b+1) - b;
printf("%d,%d",size_a,size_b);
}
int main(){
int arr[] = {2,12,14,16};
int brr[] = {8,53,2,4,16};
arrSize(arr,brr);
return 0;
}
This function declaration本 function 声明
void arrSize(int a[],int b[]){
int size_a = *(&a+1) - a;
int size_b = *(&b+1) - b;
printf("%d,%d",size_a,size_b);
}
is adjusted by the compiler to the following declaration由编译器调整为以下声明
void arrSize(int *a,int *b){
int size_a = *(&a+1) - a;
int size_b = *(&b+1) - b;
printf("%d,%d",size_a,size_b);
}
That is parameters having array types are adjusted by the compiler to pointers to array element types.也就是说,具有数组类型的参数由编译器调整为指向数组元素类型的指针。
On the other hand, in this call另一方面,在这个电话
arrSize(arr,brr);
the arrays are implicitly converted to pointers to their first elements. arrays 被隐式转换为指向其第一个元素的指针。
Having a pointer to the first element of an array you are unable to determine the array size pointed to by the pointer.拥有指向数组第一个元素的指针,您无法确定指针指向的数组大小。
the initializers in these declarations这些声明中的初始化器
int size_a = *(&a+1) - a;
int size_b = *(&b+1) - b;
invoke undefined behavior because you are dereferencing pointers that do not point to valid object.调用未定义的行为,因为您正在取消引用不指向有效 object 的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.