简体   繁体   English

检查指针是否已初始化的最佳方法

[英]Best way to check if pointer is initialized

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: 我知道我可以使用NULL初始化每个指针,然后检查:

if(ptr1 == NULL)
    do something

But is there way to write something similiar but without initialization of ptr ? 但有没有办法写一些类似但没有初始化ptr东西?

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. 确保变量初始化的唯一方法是显式地为您写入一个值(例如, NULL ),就像您在问题中已经提到的那样。

I have a struct that contains array of pointers [...] is there way to write something similar but without initialization of ptr ? 我有一个包含指针数组的struct [...]是否可以编写类似但没有初始化ptr

No. 没有。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM