Hello,

I have the following setup, where vertexArray is a pointer to float (float*). It is supposed to check if the pointer has been allocated memory for. If it hasn't, it should allocate memory, but if it's already been done it will go on to put values in the array.

int arrayLength = 10; (not really but just for showing that it has a value)

if (vertexArray == 0)
{
        vertexArray = new float[arrayLength];
}

now, the first time this function is called vertexArray does not get allocated memory for, so the application crashes. Why doesn't it work? I've been told it should, and I've also tried with checking if it's NULL. Same result.

Thanks!

It could happen if 'vertexArray' pointer is containing some junk. When you declared it you should assign it to NULL explicitly.

float* vertexArray = NULL;
int const len = 10;
float * vertexArray[len] = {0};

initializes all vertexArray[] entries with 0

If you dynamically allocate the array you have to do something like:

float* vertexArray = 0;
...
if (!vertexArray)
{
    vertexArray = new float[len];
    std::fill(vertexArray, vertexArray + len, 0);
}

You cannot declare array with a variable size.

It's true but new float[arrayLength] construct is not an array declaration: operator new creates anonymous array object, a new argument (number of elements) is an arbitrary arithmetical type expression.

This article has been dead for over six months. Start a new discussion instead.