Pointer and Array

How to differ between a pointer and an array without knowing it beforehand?
Keep in mind that your code ought to be error-free during compilation time.

This question came up from one of forums I follow. I did not know how to solve the question though. But what came first to my mind was I could differ them if I compared size of those two. The idea is a pointer could not have size more than 1 whilst an array could.
//if foo is variable we're going to check
void* ptr;

if (sizeof foo == sizeof ptr)
      cout << "foo is a pointer";   
else  cout << "foo is an array";
Unfortunately, as it was explained there , it had bug if I initialized an array with only one member.
int foo[1];
The second option was mentioned by another member. His idea was an array couldn't use arithmetic operation such as increment or decrement so it would give an error if we're doing so.
//if buf is variable we're going to check
int main (void)
     char buf[10];
It worked well, however it broke the rule stated before which is any compilation error is not acceptable. Finally, the thread starter gave the answer.
//p is variable we're going to check
if ((void*)(&p) == (void*)(&p[0]))
   printf("p is an array\n");
elseprintf("p is a pointer\n");
I smiled when I read the answer. I did not even think the answer would be that simple. If the address of a variable itself is equal to address of the first element in array, then it must be an array. Otherwise, it's a pointer. What a tricky question !



Post a Comment

It is my pleasure to get your best respond through your comment

Quotes of the Day

Recent Comments


Shev's bookshelf: read

OutliersKetika Cinta Bertasbih5 cmLaskar PelangiSang PemimpiEdensor

More of Shev's books »
Shev Save's  book recommendations, reviews, favorite quotes, book clubs, book trivia, book lists