in Programming in C edited by
412 views
3 votes
3 votes

Assume that $a[4]$ is a one-dimensional array of $4$ elements, $p$ is a pointer variable and $p = a$ is performed. Now, which among these expressions is illegal?

  1. $p == a[0]$
  2. $p == \&a[0]$
  3. $^*p == a[0]$
  4. $p[0] == a[0]$
in Programming in C edited by
by
412 views

4 Comments

can you please explain, why option a is incorrect
1
1
@aarati
Yes, you are correct .
here p is a pointer variable like int *p and p = a is performed.

p holds the address of a[0], and a[0] would hold the contents at the location.

For option A)
 p == a[0] is illegal as p is a pointer variable and holds an address .and a[0] represents the 1st element of array.
so option A is illegal.

For option B and C , both are legal , correct comparison is p == &a[0], since &a[0] would yield a pointer that points to first element of 'a'.

And *p pointing  the value holds by a[0] .

For option D)  it is also legal.

p[0] == a[0] is correct and true since in this case both the expressions p[0] and a[0] yield the content of the first element of array a.
1
1

@Bikram sir as it is mentioned in question that

a[4] is a one-dimensional array of 4 elements

it may be the case that this array "a"  is array of pointers and each element of this is pointing to addresses of differnt elements.Then if suppose a[0] is holding the address of an variable x;

then p==a[0] will be a legal action because both are addresses. 

0
0

it may be the case that this array "a"  is array of pointers

@ reena_kandari i don't think we can assume ourself whatever we want,they will specify if it is an array of pointers or atleast they give declaration like int *a[5].

0
0

1 Answer

2 votes
2 votes
Best answer


p is a pointer variable it means int *p;

after that p=a;

  • statement 1)p==a[0]


p is holding address and a[0] is holding value how this can be done . // This is illegal

  • statement 2)

p==&a[0]

p==&*(a+0)

p==a(both are holding address)

  • statement 3) *p ==a[0]

both are holding 1st value of array a .

  • statement 4) p[0]==a[0] same as previous


Therefore  statement 2,3,4 is right

answer is option A .

selected by

2 Comments

@jai ,

yes, you are correct .

int *p;

int a[4];

p = a; // so now value of p is address of first element of the array a .

then we can compare both first element like that p[0] == a[0]  // so it is a valid statement

p holds the address of a[0], and a[0] would hold the contents at the location. so p ==a[0] would not possible

as p holds address and a[0] holds value of first element of array , we can not compare them.
0
0

i am still getting error?

1
1
Answer:

Related questions