0

If we don't want the value of array to change in the main function, what can we do? For example:

    int func(int a[])
    {
         ------
         ---
    }

    int main()
    {
          int a[100];
          for (i = 0; i < 100; i++)
              scanf("%d", &a[i]);
          func(a);
    }

In this example, the values we put in the array in the main function get replaced in the func function. How to avoid this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
zev
  • 33
  • 1
  • 3

1 Answers1

3

Yes, arrays are always passed 'by reference'; the value passed is a pointer to the zeroth element of the array.

You can tell the compiler to disallow changes by making it a const:

int func(const int a[])
{
    …
    a[0] = 1;  // Compiler error - attempt to modify constant array
    …
}

Note that it is usually a good idea to pass the size of the array (the number of (used) elements in it) as an extra argument to the function:

int func(int n, const int a[n])  // C99 or later
int func(const int a[], int n)   // Classic argument order
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278