1

I think the output should be 10 10, but it is 10 1 and idk why.

I tried assigning arr[0]=55 and it made i to be 55 idk why that either. Would be glad to have an explanation

void foo(int arr[])
{
  int i=10;
  arr=&i;
  printf("%d",arr[0]);
}

int main() 
{
  int a[4]={1,2,3,4};
  foo(a);
  printf("%d",a[0]);
  return 0;
}

What i thought: 1010 actual o/p= 101

klutt
  • 30,332
  • 17
  • 55
  • 95
  • 1
    You're not doing anything with your array. First thing you do in your function is reassign the pointer to it to somewhere else. – Christian Gibbons Jul 02 '19 at 19:49
  • C is pass-by-value. When you pass a parameter to a function, the function receives a *copy-of* the variable. In the case of an array (which is converted to a pointer), the function receives a *copy-of* the pointer. (the copy contains the original memory address). However, you assign a new address to the *copy-of* the pointer and you return nothing (type `void`), so there is no way any changes made to the address of `arr` in `foo` will be seen back in `main()`. – David C. Rankin Jul 03 '19 at 02:49

2 Answers2

5

With arr=&i, you change the local pointer to the array and let it point somewhere else; yet you do not change the original array's content.

Write arr[0]=10, and it should give you the 1010 output.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
1

Basically what Stephan said. You modified the arr[0]'s address to point to the address of i. When foo finished execution, it deleted the copy of arr. The original array was copied when you passed it to the function in the parameter (c is pass-by-value language)