正确的方法来初始化在C字符串 [英] Proper way to initialize a string in C

查看:135
本文介绍了正确的方法来初始化在C字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过人们的code为:

I've seen people's code as:

char *str = NULL;

和我见过,这是为好,

char *str;

我纳闷,什么是初始化字符串的正确方法?当你应该初始化字符串瓦特/和瓦特/空?

I'm wonder, what is the proper way of initializing a string? and when are you supposed to initialize a string w/ and w/out NULL?

推荐答案

你应该在使用前进行设置。这是你的有无的跟踪,以避免不确定的行为的唯一规则。无论您是在创建时初始化它,或者只是用它无关之前分配给它。

You're supposed to set it before using it. That's the only rule you have to follow to avoid undefined behaviour. Whether you initialise it at creation time or assign to it just before using it is not relevant.

就个人来说,我preFER来从来没有设置为未知值的变量自己,所以我通常会做第一个,除非它非常接近的设置(几行内)。

Personally speaking, I prefer to never have variables set to unknown values myself so I'll usually do the first one unless it's set in close proximity (within a few lines).

在事实上,C99,在那里你不必在块顶部声明当地人更多的,我一般会推迟创建它,直到它的需要,此时它也可被初始化。

In fact, with C99, where you don't have to declare locals at the tops of blocks any more, I'll generally defer creating it until it's needed, at which point it can be initialised as well.

请注意该变量被赋予在某些情况下的缺省值(例如,如果他们是静态存储持续时间,如在文件级被宣布,任何功能外)。

Note that variables are given default values under certain circumstances (for example, if they're static storage duration such as being declared at file level, outside any function).

局部变量没有这个保证。所以,如果你的上面(的char * str中; ),第二个声明是一个函数里面,它可能有垃圾在里面,并尝试使用它会调用前面提到的,可怕的,不确定的行为。

Local variables do not have this guarantee. So, if your second declaration above (char *str;) is inside a function, it may have rubbish in it and attempting to use it will invoke the afore-mentioned, dreaded, undefined behaviour.

C99标准的相关部分6.7.8 / 10

如果具有自动存储时间的对象没有明确初始化,它的价值是不确定的。如果具有静态存储持续时间的对象不明确初始化,然后:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:


      
  • 如果有指针类型,它被初始化为空指针;

  •   
  • 如果有算术类型,它被初始化为(正或无符号)为零;

  •   
  • 如果它是一个聚合,每个成员被初始化(递归)根据这些规则;

  •   
  • 如果它是一个联盟,首批命名部件(递归)根据这些规则进行初始化。

  •   

这篇关于正确的方法来初始化在C字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆