0

When I run this program-

#include <stdio.h>
void inc( int num[], int n)
{
  int i;
  n++;
  for(i=0;i<10;i++)
    num[i]++;
}

int main()
{
  int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
  int a=2;
  inc (arr, a);
  int i; 
  for(i=0;i<10;i++)
    printf("%d  ", arr[i]); 
  printf("\n%d  ", a);
return 0;
}

I get the output-

2  3  4  5  6  7  8  9  10  1                                                                                                                  
2

I understand why the int is unchanged but I don't understand why the array is getting changed since I have not used pointers to call the array. I know that the function will make a different copy of n and assign n=a and all changes will happen to n only and a will be unchanged. Why the array is getting changed?

1 Answers1

0

In C, except for a few cases, an array name decays (=gets implicitly converted) to a pointer to its first element.

This

void inc(int num[], int n)

is exactly same as this:

void inc(int *num, int n)
Swordfish
  • 12,971
  • 3
  • 21
  • 43
H.S.
  • 11,654
  • 2
  • 15
  • 32
  • [C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)](http://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3) – David C. Rankin Nov 24 '18 at 08:16