Can not understand the pointer mechanism

advertisements

Why is the program below crashing? I tried debugging the code but couldn't understand; I am suspecting that either the program is wrong or the memory to the passed pointer to display function should have been initialized.

#include <iostream>
using namespace std;

int display( int** intarray )
{
    int size = 0;
    while( size < 10 )
    {
        *intarray[size] = size;
        size++;
    }

    return size;
}

int main() {
    int* intptrarray;
    int arraysize = 0;
    arraysize = display( &intptrarray );

    for ( int indx = 0; indx < arraysize; indx++ )
    {
        std::cout << intptrarray[indx] << std::endl;
    }
    return 0;
}


*intarray[size] should be (*intarray)[size].

However you have not yet allocated any memory either, so in both cases you are causing undefined behaviour by writing through an uninitialized pointer.

A correct way to write this program is:

void display( std::vector<int> &vec )
{
    vec.resize(10);
    for ( int i = 0; i < 10; ++i )
        vec[i] = i;
}

int main()
{
    std::vector<int> vec;
    display(vec);

    for ( int indx = 0; indx < vec.size(); indx++ )
    {
        std::cout << vec[indx] << std::endl;
    }
}

This can be improved by using std::iota and range-based for-loops if you have a modern compiler.