# Difference between Pointer Arithmetic on Structures and Pointer Arithmetic on Arrays in C

Question: How Pointer Arithmetic on Structures Differs from Pointer Arithmetic on Arrays in C Programming?

Answer: This can better be understood by considering an example,

```struct A {
int a;
float b;
char c[3];
};

int main(void)
{
struct A x = {10, 23.33, "hi"};
struct A *p2x = &x;    /* 'p2x' is pointing to 'x' */

return 0;
}```

Notice that ‘p2x’ is pointing to structure ‘x’. Then exp., for example,

`    p2x + 1;`

results what? We know from pointer’s arithmetic that in exp.

`    p2x + 1;`

1 is adjusted and added to value of ‘p2x’, which results in a value, an address, pointing to location immediately after structure ‘x’. Since, ‘x’ is a scalar and not a vector, therefore, it points to unidentified location. And we can’t know what could be there whether a structure of same type of something else! But if ‘x’ had been an array of structures, exp.

`    p2x + 1;`

would point to next element in the array i.e. next structure. Be careful while writing such expressions because compilers don’t check such restrictions for you.

Notice the last member of ‘x’ is a string “hi”. Let’s access this through ‘p2x’,

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
`    p2x->c;`

What’s the type of exp. p2x->c? This is character array or we can say it’s pointer to char! And as we know that an array is a pointer constant. This is not a valid L-Value! Let’s consider R-Value of the exp.

`   p2x->c;`

The below exp.

`    p2x->c[0];`

refers to first character ‘h’ of string “hi”, while

`    p2x->c[1];`

refers to ‘i’ in “hi”. Explanation is simple! In exp.

`   p2x->c[0];`

we performed indirection on p2x->c using the subscript value 0. And result is character ‘h’ where pointer p2x->c was pointing to. The equivalent exp. for

`    p2x->c[0];`

could be rewritten as

`    *(p2x->c + 0);`

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]