trungnt
trungnt

Reputation: 1111

Finding the address of first and last byte of a given index within an array

I'm wondering whether my answer to the following question is correct:

Suppose you have an "int" array declared as: int myArray[20]. The fi rst byte in the array has the address 1010. What are the addresses of the first and last bytes of myArray[13]? The size of int is 4 bytes.

That means that each index within this array takes up 4 bytes correct? If that's the case, myArray[13] would start 4x13 = 52 bytes after myArray[0]? Meaning that the first byte would be located at address 1062 and the last byte would be 1065?

Upvotes: 0

Views: 758

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

They're

static_cast<char*>(&myarray[13])

and

static_cast<char*>(&myarray[14]) - 1

no?

Yes, your calculations are correct. Be careful with your assertion that sizeof(int) is 4, though: I couldn't tell whether you were pointing out a proven fact of your platform, or whether you thought this was a universal constant (which it isn't).

Upvotes: 2

Related Questions