Hi,
Had 2 questions about this little program I typed in from a book I'm using to learn C++:
Code:
/* The pattern matching algorithm uses 2 loops. The outer loop
is controlled by the pointer p1 which points to elelments in array
a1 where the inner loop will begin checking for a match with array
a2. The inner loop is controlled by the integer j which is used
to compare corresponding elelments of the 2 arrays. If a mismatch
is found, the inner loop aborts and the outer loop continues by
incrementing p1 to look for a match starting with the next element
of a1. If the inner loop is allowed to finish, then the condition
(j = n2) will be true and the current location pointed to by p1 is
returned. The test driver verifies that the match has indeed been
found by checking the actual addrsses. */
#include <iostream>
#include <stdlib.h>
using namespace std;
short* loc(short* a1, short* a2, int n1, int n2)
{ short* endl = a1 + n1; // ???? if a1 = a[0],
// then wouldn't this make endl point to a[9]?
// Isn't a[0] = a[0] ... a[8]??
for (short* p1 = a1; pl < endl; pl++)
if (*pl == *a2)
{ int j;
for (j = 0; j < n2; j++)
if (p1[j] != a2[j]) break;
if (j == n2) return p1; // ??? if j == n2 (or 5), how can
// that be since the for loop only allows j < n2?
}
return 0;
}
int main()
{ short a1[9] = {11, 11, 11, 11, 11, 22, 33, 44, 55};
short a2[5] = {11, 11, 11, 22, 33};
cout << "Array a1 begins at location:\t" << a1 << endl;
cout << "Array a2 begins at location:\t" << a2 << endl;
short* p = loc(a1, a2, 9, 5);
if (p)
{ cout << "Array a2 found at location:\t" << p << endl;
for (int i = 0; i < 5; i++)
cout << "\t" << &p[i] << ": " << p[i]
<< "\t" << &a2[i] << ": " << a2[i];
}
else cout << "Not found.\n";
system("pause");
return 0;
}
// ???? if a1 = a[0],
// then wouldn't this make endl point to a[9]?
// Isn't a[0] = a[0] ... a[8]??
// ??? if j == n2 (or 5), how can
// that be since the for loop only allows j < n2?
Dumb question or not, it just really confused me when I thought I almost completely understood the way this piece of code worked. I appreciate your help.
Swaine777