-1

Why pointer X and Y have to be passed in the lcs function? Also what is going wrong when instead of a pointer an array is passed.

#include<stdio.h>
#include<string.h>

int max(int a, int b);

int lcs( char* X, char* Y, int m, int n )
 {
  if (m == 0 || n == 0)
  return 0;
  if (X[m-1] == Y[n-1])
  return 1 + lcs(X, Y, m-1, n-1);
else
  return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}

int max(int a, int b)
{
  return (a > b)? a : b;
}

int main()
 {
 char X[] = "AGGTAB";
 char Y[] = "GXTXAYB";

 int m = strlen(X);
 int n = strlen(Y);

 printf("Length of LCS is %d", lcs( X, Y, m, n ) );

 return 0;

}

zaxcode
  • 17
  • 3

1 Answers1

2

Whenever you pass an array to a function it is converted into a pointer to the first element of it. And as it contains the address of the first element using it we can change the array from another function. This is known as array decaying. Even if you don't want to change the array it will be converted into a pointer.

To summarize, it's not possible to pass an array without going through this conversion to a pointer. That's what you saw here. From C11 standard (N1570) we can quote this also:-

ยง 6.3.2.1p3

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

user2736738
  • 30,591
  • 5
  • 42
  • 56