Calculate memory address by pointer arithmetic

Asked

Viewed 455 times

2

Suppose the elements of the vector v are of the type int and each int takes 8 bytes on your computer.

If the address of v[0] is 55000, what is the value of the expression v + 3?

2 answers

4


I will follow your assumptions, although this does not usually occur in fact.

Like v is a pointer the arithmetic will be made on top of the elements it points to. Zero is always the beginning of the sequence (as is the case), and at the same time it is the first element of it. So if 0 is the first element, and of course 1 is the second, we can conclude that 3 is the fourth element.

The statement says that the pointed element has 8 bytes, so each element displaces 8 bytes.

The bill should be v plus the element number times 8. Then the expression v + 3 will result in 55024, which is the memory position which is the fourth element of the sequence.

This applies to C and the basic use of C++, but in the latter the semantics may be another according to the vector type encoding.

1

The v + 3 will result in the memory position of v[3]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.