Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if pointer is initialized

Tags:

c

pointers

Is there a way to check if pointer was initialized? I have a struct that cointain array of pointers

typedef struct foo
{
    int* ptr1;
    int* ptr2;
    int* ptr2;
    ...
    int* ptr100;
}

and then my code is assigning adresses to those pointers (inside loop). But before adress is assigned i want to check if pointer is already containing adress. I know that i can initliazie every pointer with NULL and then check this with:

if(ptr1 == NULL)
    do something

But is there way to write something similiar but without initialization of ptr?

like image 976
susi33 Avatar asked Mar 06 '16 12:03

susi33


People also ask

How do you check if a pointer has been initialized?

You can't know that. An uninitialized variable could have any value (including maybe 0). You have to just always initialize your variables and you won't have this problem. Note that it only really occurs with POD types (basically built-in types like int, char, pointers, etc.).

How pointer is initialized?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.

How do you test a pointer?

The technique is to use MIN and MAX to specify that the pointer should be between the address of the first element and the address of the last element of the string. However by default pointers can only be tested for equality and a warning message will be issued if you try to use MIN and MAX.

What is pointer in C how it is initialized?

A pointer can also be initialized to null with any integer constant expression that evaluates to 0 , or with the nullptr keyword. . Such a pointer is a null pointer and it does not point to any object. For more information about the null pointer, see Null pointers.


2 Answers

An uninitialized variable can contain any value. Therefore, it is not possible to find out if a variable is uninitialized as it can look just like an already initialized variable. The only way to make sure that a variable is initialized is to explicitly write a value (for example, NULL) to it as you already noted in your question.

like image 127
fuz Avatar answered Nov 12 '22 07:11

fuz


I have a struct that contains array of pointers [...] is there way to write something similar but without initialization of ptr?

No.

Related: https://stackoverflow.com/a/19626617/694576

like image 1
alk Avatar answered Nov 12 '22 08:11

alk