Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `*a` and `a[0]`?

Tags:

c++

Given a user-defined type A, and a pointer A* a, what is the difference between *a and a[0]?

(Though *(a+0)/a[0] are defined to be equivalent, the same is not the case for *a/a[0], where a subtle difference may cause a compilation error in certain circumstances.)

like image 397
Lightness Races in Orbit Avatar asked Jan 23 '13 19:01

Lightness Races in Orbit


People also ask

What is the difference between 0 and 0 in Python?

Python returns the first character of a string when either of these are used as index values. 0 and -0 are the same.

What is &A in C programming?

In C “&” stands for ampersand. & is written before any variable because it shows the address of variable where the value will save or what is the address of a. Just like if you write suppose “a” is variable and its integer type. scanf(“%d”,&a) ; this will scan a integer value and save it into the address of variable a.


1 Answers

If A is an incomplete type, *a works, but a[0] does not, in this example:

struct A;

void foo(A& r)
{
}

void bar(A* a)
{
    foo(*a);
    foo(a[0]);   // error: invalid use of incomplete type ‘struct A’
}

That's because a[0] is equivalent to *(a+0), but you cannot add something to a pointer to an object of incomplete type (not even zero), because pointer arithmetic requires the size to be known.

like image 141
fredoverflow Avatar answered Nov 15 '22 19:11

fredoverflow