简体   繁体   English

我们如何找到以下C程序的输出?

[英]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: 以下是我对此代码的解释:

  1. Firstly, the main function will run, in which after declaring the array "arr", next statement will execute which contains the statement fun(arr). 首先,将运行main函数,在声明数组“arr”之后,将执行包含语句fun(arr)的下一个语句。
  2. In that statement, the function "fun" will be called with the argument arr, which contains the address of the first element of the array. 在该语句中,函数“fun”将使用参数arr调用,该参数包含数组的第一个元素的地址。
  3. After that, under the function fun, there is a pointer ptr as a parameter. 之后,在函数fun下,有一个指针ptr作为参数。 When this function will execute, then the value of n will be calculated as 1 since here the size of ptr is 4 and the size of ptr[0] is also 4. 当执行此函数时,n的值将计算为1,因为此处ptr的大小为4,ptr [0]的大小也为4。
  4. Next, the loop will run only once since the value of n is 1 and that's why only '1' will get printed since it is the value of ptr[0]. 接下来,循环将仅运行一次,因为n的值为1,这就是为什么只有'1'将被打印,因为它是ptr [0]的值。

Please help me to find out where I am wrong. 请帮我弄清楚我错在哪里。

  • [....] the value of n will be calculated as 1 since here the size of ptr is 4 and the size of ptr[0] is also 4 . [......] n的值将计算为1因为此处ptr的大小为4ptr[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)可以计算为4n的值为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) == 4n == 1
On a 64-bit platform it's likely that sizeof(ptr) == 8 and n == 2 . 在64位平台上, sizeof(ptr) == 8n == 2

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

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