-1

So I have these statements in my code(there are many other lines but this is giving me trouble):

int *vector1;

if (vector1 == NULL)
    {

    }

When I try to run it it says "uninitialized local variable 'vector1' used" If I put "&vector1 == NULL" it doesn't complain but also doesn't work correctly.

I really don't understand why I am getting this error. I want it to do something if vector1 doesn't point to anything.

Pongjazzle
  • 67
  • 1
  • 6

2 Answers2

2
int *vector1 = NULL;
if (vector1 == NULL)
{

}

will work fine

int *vector1 = nullptr;
if (vector1 == nullptr)
{

}

Also works if you want to be a bit more up to date.

Pointers are not set to NULL by default. The answer why is here: Why aren't pointers initialized with NULL by default?

Community
  • 1
  • 1
marsh
  • 2,592
  • 5
  • 29
  • 53
1

The warning uninitialized local variable 'vector1' used tells you that you're using vector1 even though you haven't initialized it. Therefore, its value might be anything.

Pointers (non-static ones) are not default-initialized to 0. They are initialized with random junk data.

If you want to initialize it with 0, NULL, or nullptr (all the same thing):

int *vector1 = 0; // or NULL, or nullptr.
Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157