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
?
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.).
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.
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.
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.
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.
I have a
struct
that contains array of pointers [...] is there way to write something similar but without initialization ofptr
?
No.
Related: https://stackoverflow.com/a/19626617/694576
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With