Alex James
Alex James

Reputation: 33

How does *(array + 3) work?

I am studying for my midterm. this was an example code

#include <stdio.h>
void doubleArray(int array[], int length) 
 {
for (int i = 0; i < length-2; i++) {
        array[i] += array[i];
 }
     length += 5;
     printf(“%d\n”, length); // Question 29
 }


int main(int argc,char *argv[]) {
     int integers[6] = { 3, 4, 5, 6, 7, 8};
     int length = 6;


printf(“%d\n”, integers[4]); // Question 28
doubleArray(integers, length);
printf(“%d\n”, *(integers + 3)); // Question 30
printf(“%d\n”, *(integers + 4)); // Question 31
printf(“%d\n”, length); // Question 32
}

for questions 30 and 31 the answer is that it prints 12 (30) and 7 (31) can someone explain to me why and what that "*(integers + 3)" means?

Upvotes: 1

Views: 509

Answers (1)

arcyqwerty
arcyqwerty

Reputation: 10685

* is a dereference operator on a pointer.

This means that it will "get" the value that's stored at the pointer address of the item right after it ((integers + 3)).

It will interpret this value as the dereferenced type of the item after it (int since (integers + 3) is of type int*)

(integers + 3)

integers is a pointer to the address of the first element of the integers array.

That means that if integers contained [1, 2, 3, 4, 5] then it would point to where 1 is stored in memory.

integers + 3 takes the address of integers (i.e. where 1 is stored in memory) and adds the amount of address space required to store 3 ints (since the pointer is of type int*). Advancing it by one space would give you the address of 2 in memory, advancing it by two spaces would give you the address of 3 in memory, and advancing it by three spaces gives you the address of 4 in memory.

How this applies to your example

(integers + 3) gives you the address of the 4th item in the integers array since it's the first element's address plus the size of three elements.

Dereferencing that with the * operator, gives you the value of the 4th element, 12 (since the value of 6 was doubled by doubleArray)

The same applies to *(integers + 4) except that doubleArray didn't double the 5th element so it gives you 7.

How doubleArray works

for (int i = 0; i < length-2; i++) means start the variable i at 0 and advance it until it is length - 2.

This means it takes the value of everything from 0 to the value of length - 2 but executes the body of the loop for values from 0 to length - 3 since the < is exclusive (the conditional is evaluated BEFORE executing the body of the loop so when i == length - 2 the condition is false and the loop terminates without further execution.

So, for each element, excluding the last two, the element in array is added to itself.

Upvotes: 2

Related Questions