Invalid Pointer Comparisons

1.Invalid Pointer Comparisons

Comparisons between pointers that do not access the same array are generally invalid, and often cause errors. You should not make assumptions about where your data will be placed in memory, whether it will always be in the same place, or whether every compiler or execution environment will treat it in the same way. Therefore, making any comparisons between pointers to two different objects may yield unexpected results. Here is an example:
char s[80];
char y[80];
char *p1, *p2;
p1 = s;
p2 = y;
if(p1 < p2) . . .
This code is based on an invalid concept since C++ makes no guarantees about the placement of variables in memory. You should write your applications in such a way that they work no matter where data is located. A related error assumes that two back-to-back arrays can be indexed as one simply by incrementing a pointer across the array boundaries. For example:
int first[10];
int second[10];
int *p, t;
p = first;
for(t=0; t<20; ++t) {
*p = t;
The aim here is to initialize arrays first and second with the numbers 0 through 19, but the code is not reliable. Even though it may work with some compilers under certain circumstances, it assumes that both arrays will be placed back-to-back in memory with first first. However, C++ does not guarantee how variables will be located in memory.
Share on Google Plus