简体   繁体   English

C编程中数组中的星号

[英]Asterisk in an array in C Programming

What is the difference between sizeof(arr) and sizeof(*arr) in C. C中sizeof(arr)和sizeof(* arr)有什么区别

int arr[] = { 1, 2, 0, 5, 5 };
int n = sizeof( arr ) / sizeof( *arr );

sizeof(arr) is the size of the entire array. sizeof(arr)是整个数组的大小。 In your case, it is the size of 5 integers. 在您的情况下,它是5个整数的大小。 In case int is 4 bytes it is 5 * 4 = 20. 如果int是4个字节,则它是5 * 4 = 20。

*arr is the first element of the array. *arr是数组的第一个元素。 It is equal to arr[0] . 它等于arr[0] sizeof(*arr) is the size of this element. sizeof(*arr)是此元素的大小。 In your case it is 4 bytes. 您的情况是4个字节。

So sizeof( arr ) / sizeof( *arr ); 所以sizeof( arr ) / sizeof( *arr ); will give the number of elements in the array. 将给出数组中元素的数量。

You should note that this will only work in the scope where the array is defined. 您应注意,这仅在定义数组的范围内有效。 If you are passing the array to a function, the arr will decay into a pointer and sizeof (arr) will only give you the size of a pointer in your system (typically 4 or 8 bytes). 如果将数组传递给函数,则arr将衰减为指针,而sizeof (arr)仅会为您提供系统中指针的大小(通常为4或8个字节)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM