[英]How do we find the output of the following C program?
I was finding the output of the following C program, which I found on GeeksforGeeks. 我找到了以下C程序的输出,我在GeeksforGeeks上找到了它。 Here's the program: 这是程序:
#include <stdio.h>
void fun(int ptr[])
{
int i;
unsigned int n = sizeof(ptr)/sizeof(ptr[0]);
for (i=0; i<n; i++)
printf("%d ", ptr[i]);
}
// Driver program
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
fun(arr);
return 0;
}
The output of this code was " 1 2 ". 此代码的输出为“ 1 2 ”。 But according to me, the output should be just 1 . 但据我说,输出应该只有1 。 Here is my interpretation of this code: 以下是我对此代码的解释:
Please help me to find out where I am wrong. 请帮我弄清楚我错在哪里。
- [....] the value of
n
will be calculated as1
since here the size ofptr
is4
and the size ofptr[0]
is also4
. [......]n
的值将计算为1
因为此处ptr
的大小为4
,ptr[0]
的大小也为4
。
Well, that's common, but not guaranteed . 嗯,这很常见,但不能保证 。
sizeof(ptr)
could very well be, result in 8
, which is likely in your case, while sizeof(int)
can evaluate to 4
, resulting a value of 2
for n
. sizeof(ptr)
很可能是8
,这可能是你的情况,而sizeof(int)
可以计算为4
, n
的值为2
。 This depends on (and varies with) your environment and used implementation. 这取决于(并随之改变)您的环境和使用的实施。
Try printing them separately, like 尝试单独打印,如
printf("Pointer size :%zu\\n", sizeof(ptr));
printf("Element size: %zu\\n", sizeof(ptr[0]));
and see for yourself. 并亲眼看看。
The size of a pointer on modern platforms is commonly either 4 or 8 bytes. 现代平台上指针的大小通常为4或8个字节。
On a 32-bit platform it's likely that sizeof(ptr) == 4
and n == 1
. 在32位平台上, sizeof(ptr) == 4
和n == 1
。
On a 64-bit platform it's likely that sizeof(ptr) == 8
and n == 2
. 在64位平台上, sizeof(ptr) == 8
和n == 2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.