Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we find the output of the following C program?

Tags:

c

pointers

sizeof

I was finding the output of the following C program, which I found on 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". But according to me, the output should be just 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).
  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.
  3. After that, under the function fun, there is a pointer ptr as a parameter. 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.
  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].

Please help me to find out where I am wrong.

like image 486
WarWithSelf Avatar asked Dec 03 '22 13:12

WarWithSelf


1 Answers

  • [....] 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.

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. 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.

like image 98
Sourav Ghosh Avatar answered Dec 28 '22 13:12

Sourav Ghosh