Connecting Tech Pros Worldwide Forums | Help | Site Map

Confused about this question!!

Newbie
 
Join Date: Jun 2009
Posts: 14
#1: Jun 18 '09
Hello,

I need assistance on this question.

Suppose that a is a one-dimensional array and p is a pointer variable. Assuming that the assignment p = a has just been performed, which of the following expressions are illegal because of mismatched types? Of the remaining expressions, which are true (have a nonzero value)?

a) p == a[0]
b) p == &a[o]
c) *p == a[0]
d) p[0] == a [0]


I assume that b and d are true from the given information. I just need a little clarification on the definitions of the given equations - the book fails to give any pre-existing examples to help tackle the problem.

Thanks.

Needs Regular Fix
 
Join Date: Jul 2008
Posts: 385
#2: Jun 19 '09

re: Confused about this question!!


b) is also true if you replace letter 'o with zero - p points to the first item in array that is address (&) of the first item of the array.
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#3: Jun 19 '09

re: Confused about this question!!


Answer c) is also correct

kind regards,

Jos
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 831
#4: Jun 19 '09

re: Confused about this question!!


Your first question was which of the expressions are illegal due to mismatched types. We already know that expressions (b), (c), and (d) must be legal since it has already been established that they all evaluate to a nonzero value.

Expression (a) is illegal because it attempts to compare a pointer to the thing being pointed at ... unless the elements of the array are of type 'void *'. Expression (a) would even evaluate to a nonzero value if each element of the array (or at least the first one) contained its own address.

By the way, the legality of (c) and (d) depend on what type of pointer variable p is declared as. These expressions are illegal if p is declared as a 'void *' because in that case there would be no way to dereference the pointer.

So ... my conclusion is that only expression (b) is definitively legal. The legality of the other expressions can't be determined without making assumptions that aren't given in the problem statement.
Newbie
 
Join Date: Jun 2009
Posts: 14
#5: Jun 19 '09

re: Confused about this question!!


Ah. Now I understand. Thanks!
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 831
#6: Jun 19 '09

re: Confused about this question!!


By the way, C and C++ have different rules for whether a legal statement can implictly convert between a specific pointer type and a 'void *' pointer type. That means the answer to your question is subtly different for the two languages.
Reply