Kev Jam
Kev Jam

Reputation: 13

Memory in C pertaining to pointer arithmetic

I'm currently reading a book on C pointers and there is an example in the book that confuses me:

Suppose we have: int arr_of_int[] = {5,10,15}; and we set: int *add_of_arr = arr_of_int;

then I know that the "add_of_arr" variable holds the address of: arr_of_int[0]; and let's just suppose the address of "add_of_arr" is 500.

Now, if I do: "add_of_arr += 3;" then the address of "add_of_arr" is now 512? That's what I'm getting from the book, but shouldn't the address of "add_of_arr" still be 500 and only the address HELD by add_of_arr be 512? What i'm getting from the book is that the address of add_of_arr is changing. This confuses me. I'm thinking it's a mistake but I'm not sure.

Thanks!

Upvotes: 1

Views: 162

Answers (2)

Norbert Paul
Norbert Paul

Reputation: 1

You are confounding two things: A pointer is a variable to store a memory address. As a variable it also has its own address where it resides in memory. As you said, let this be 500. The expression add_of_arr=arr_of_int hence copies the address of arr_of_int[0] into memory location 500. Now assume, arr_of_int is at memory location 400. Then add_of_arr=arr_of_int stores 400 into memory location 500. After add_of_arr += 3 your pointer at memory location 500 contains 412. The address of add_of_arr (obtained by &add_of_arr) however still is 500 but its value (obtained by add_of_arr) has changed from 400 to 412.

Upvotes: 0

Andriy Berestovskyy
Andriy Berestovskyy

Reputation: 8544

It is a typo: address in add_of_arr is now 512, but the address of add_of_addr has not changed.

Upvotes: 3

Related Questions