Quick question about arrays and pointers in c++

Discussion in 'Programmer's Corner' started by asilvester635, Feb 8, 2017.

  1. asilvester635

    Thread Starter Member

    Jan 26, 2017
    68
    3
    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 (Text):
    1.  
    2. int array[8];
    3.     array[0] = 10;
    4.  
    5.     // get and print size of the array
    6.     int size = sizeof(array) / sizeof(array[0]);
    7.     printf("Size is %d\n", size);
    8.  
    9.     // this is accessing some address because the value stored inside end changes every time we run the program?
    10.     int* end = array + 8;
    11.  
    12.     for (int* elem = array; elem < end; ++elem) {
    13.         *elem = 6;
    14.     } // end of for loop
    15.  
    16.     // print contents inside the array
    17.     for (int i = 0; i < size; i++) {
    18.         printf("%d\n", array[i]);
    19.     } // end of for loop
    20.  
     
  2. AlbertHall

    Distinguished Member

    Jun 4, 2014
    3,610
    818
    '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.
     
Loading...