-2

I found this code in internet.And i am confused from 1 hour. What i found weird is that array b[] is inside met2() function with local scope. And there is another array a[] which is inside met1() function with it's local scope . But How could value of a[] is transferred to b[] array. And Most importantly, both function are not returning any values. This is so confusing. Please Help me out here. I searched online but nobody had asked such questions.

#include <stdio.h>
int main()
{
    met2();
    return 0;
}
void met1(int a[1])
{
    a[0]=199;
}
void met2()
{
    int b[1];
    met1(b);
    printf("%d",b[0]);
}
Arjun Bhat
  • 15
  • 5

2 Answers2

0

Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" is converted ("decays") to an expression of type "pointer to T" and the value of the expression is the address of the first element of the array.

When you call

met1(b);

the expression b is converted from type "1-element array of int" to type “pointer to int", and the value of the expression is the address of b[0].

In the function prototype

void met1(int a[1])

the parameter declaration int a[1] is "adjusted" to int *a - it’s actually being declared as a pointer (which is handy, since that’s what the function actually receives).

So whenmet2 calls met1, it’s passing the address of the first element of b. The [] operator can be used on pointers as well as arrays (it’s actually defined in terms of pointer arithmetic - a[i] is interpreted as *(a + i)).

So writing a[0] = 199; in met1 is equivalent to writing b[0] = 199; in met2.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

The key here is to understand that whenever we declare an array as parameter of a function, it gets adjusted to a pointer to its first element. C17 6.7.6.3 emphasis mine:

A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.

This means that void met1(int a[1]) and void met1(int* a) are 100% equivalent. The former gets silently translated to the latter by the compiler.

This is quite confusing because int a[1] looks like an array declaration and one might easily get idea the idea that the array is passed by value. But passing arrays by value isn't possible in C.

In your case, the local array b gets passed to met1 as a pointer to its first element. With a[0] = ... that pointed-at element is changed.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Thank you sir.. That is very helpful for me. I have learned great lessons from you guys. I will do more reaching out, if i stuck on some problems. – Arjun Bhat Oct 14 '19 at 10:27