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

1
  • &vector1 is never null. why don't you just initialize vector1. Commented Mar 1, 2015 at 3:06

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

3 Comments

of course, that (vector1==NULL) is always true...
Ah, that makes sense. However, I thought when pointers were created they inherently pointed to NULL?
No that is not true, they will point to garbage data. I have udpated my post with a link to as why.
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.

2 Comments

static variables are initialized to zero stackoverflow.com/questions/13251083/…
@RichardChambers yea

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.