How to find the output of the next program?

I found the output of the following C program that I found on GeeksforGeeks. Here is 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 result of this code was " 1 2 ". But for me, the output should be only 1 . Here is my interpretation of this code:

  • First, the main function will be launched, in which, after declaring the array "arr", the next statement containing the fun (arr) instruction will be executed.
  • In this statement, the fun function is called with the arr argument, which contains the address of the first element of the array.
  • After that, under the fun function, there is a ptr pointer as a parameter. When this function is executed, the value of n will be calculated as 1, since here the size ptr is 4, and the size ptr [0] is also 4.
  • , , n 1 "1" , ptr [0].

, , .

+4
2
  • [....] n 1, ptr 4, ptr[0] 4.

, , .

sizeof(ptr) 8, , , , sizeof(int) 4, 2 n. ( ) .

,

  • printf("Pointer size :%zu\n", sizeof(ptr));
  • printf("Element size: %zu\n", sizeof(ptr[0]));

.

+10

4 8 .

32- , sizeof(ptr) == 4 n == 1.
, 64- sizeof(ptr) == 8 n == 2.

+7

Source: https://habr.com/ru/post/1677284/


All Articles