Quick question about arrays and pointers in c++

Thread Starter

asilvester635

Joined Jan 26, 2017
73
What is being stored inside int* end in this statement? ----> int* end = array + 8;
I'm guessing that it's the memory address since I tried printing out the content inside *end, and the value printed changes every time I run the program. array gives the address, and the + 8 gives it 8 storage locations?

Code:
int array[8];
    array[0] = 10;

    // get and print size of the array
    int size = sizeof(array) / sizeof(array[0]);
    printf("Size is %d\n", size);

    // this is accessing some address because the value stored inside end changes every time we run the program?
    int* end = array + 8;

    for (int* elem = array; elem < end; ++elem) {
        *elem = 6;
    } // end of for loop

    // print contents inside the array
    for (int i = 0; i < size; i++) {
        printf("%d\n", array[i]);
    } // end of for loop
 

AlbertHall

Joined Jun 4, 2014
8,181
'array' is the address of the first element of the array. The '+8' adds 8 times the size of an int (because it is an int pointer so it knows the size). so 'array+8' is the address immediately following the last element of the array. The 'for' line uses 'elem' from the start address of the array to one less than 'end', i.e. the last element of the array.
 
Top