In the following code snippet, T represents a class. This code is claimed to have problem due to the fact that "p" will be out of range after running "*p=a". Why?

void f1(T a)
{
   T v[200];
   T*  p = &v[0];
   p--;
   *p=a;
   ++p;
   *p=a;
}

Recommended Answers

All 2 Replies

void f1(T a)
{
   T v[200];
   T*  p = &v[0];
   p--;
   *p=a;
   ++p;
   *p=a;
}

It is due to pointer "p" which after being decrementing would point to some random memory which is not of type T.

commented: Thats the simplest answer to the problem. +2

The problem is that p will be pointing to some out-of-range memory location and that has nothing at all to do with whether its of type T or not. You will get the same error if you try to do the same thing in a simple C program. C and C++ languages do not normally support storing data before the address of the array, although it is common to do that in BSTR data types (Microsoft specific data type). Some other languages such as VB might do that too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.