Krishna
Krishna

Reputation: 1382

Unable to understand the pointer mechanism

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;
}

Upvotes: 0

Views: 64

Answers (2)

user3148225
user3148225

Reputation: 425

When a pointer is declared, it doesn't point to any specific memory address. To have it point somewhere, you need to allocate memory to it as follows:

#include <iostream>
using namespace std;

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

    return size;
}

int main() {
    int arraysize = 10;
    int* intptrarray = new int[arraysize];

    arraysize = display( &intptrarray, arraysize );

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

    delete[] intptrarray;
    return 0;
}

Whenever you allocate memory, you need to remember to deallocate it yourself (delete for a single variable, delete[] for an array).

Upvotes: 1

M.M
M.M

Reputation: 141554

*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.

Upvotes: 0

Related Questions