开发者

How to test is a string is initialized in c?

Quick and easy C question: char* foo

How can I test if foo 开发者_运维问答hasn't still been assigned a value?

Thanks.


You can't.

Instead, initialize it with NULL and check whether it is NULL:

char *foo = NULL;
...
if(!foo) { /* shorter way of saying if(foo == NULL) */


You can't test at runtime in a platform-independent way. Doing anything with an uninitialized value other than assigning to it is undefined behaviour. Look at the source and analyse the code flow.

It may be that your compiler initialises stack memory with a particular value, and you could test for this value. It's not portable even to the same compiler with different flags (because the standard doesn't require it, and it might only happen in debug mode), and it's not reliable because you might have assigned the "magic" value.

What you'd normally do in this case is initialize the pointer to NULL (equivalently, 0), then later test whether it is NULL. This doesn't tell you whether you've assigned NULL to it or not in the intervening time, but it tells you whether you've assigned a "useful" value.


Your variable is defined/declared just not initialized. You can check if your variable has a value by first initializing it when you declare it. Then later you can check if it has that initial value.

char *foo = NULL;


//...

if(foo)
{
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜