热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Whichismoreefficient:charstr[]orchar*str?

Thisarticlediscussestheefficiencyofusingcharstr[]andchar*strandwhetherthereisanyreasontopreferoneovertheother.Itexplainsthedifferencebetweenthetwoandprovidesanexampletoillustratetheirusage.

For the sake of efficiency, is there ever a reason to use one of these over the other?

为了提高效率,是否有理由使用其中一种而不是另一种?

char str1[] = "Hello"
char *str2  = "World"

1 个解决方案

#1


4  

They do two different things.

他们做了两件不同的事情。

char str1[] = "Hello";

is equivalent to

相当于

char str1[6] = "Hello";

It makes str1 an array of 6 chars, initialized to "Hello" plus a '\0' terminator.

它使str1成为一个包含6个字符的数组,初始化为“Hello”加上一个'\ 0'终止符。

This:

char *str2  = "World";

makes str2 a pointer to char, pointing to the first element of a statically allocated read-only array of 6 chars, which is initialized to "World" plus a '\0' terminator.

使str2成为指向char的指针,指向静态分配的6个字符的只读数组的第一个元素,该数组初始化为“World”加上一个'\ 0'终止符。

I mentioned that the array is read-only -- but for historical reasons it's not actually const; attempting to change it has undefined behavior. You should define it as const so the compiler will warn you if you incorrectly attempt to modify it:

我提到数组是只读的 - 但由于历史原因,它实际上不是常量;试图改变它有未定义的行为。您应该将其定义为const,以便编译器在您错误地尝试修改它时会发出警告:

const char *str2 = "World";

str1 and str2 can be used interchangeably in some, but not all, contexts. For example, either puts(str1) or puts(str2) will print the corresponding string to standard output (followed by a newline). This is because an array name, in most contexts, "decays" to a pointer to the array's first element.

str1和str2可以在一些但不是所有的上下文中互换使用。例如,put(str1)或puts(str2)将相应的字符串打印到标准输出(后跟换行符)。这是因为在大多数情况下,数组名称“衰减”到指向数组第一个元素的指针。

Since str1 is an array, you can apply sizeof to it to determine how big the array is; sizeof str2 gives you the size of a char* pointer, which probably won't be useful.

由于str1是一个数组,您可以对其应用sizeof来确定数组的大小; sizeof str2为您提供char *指针的大小,这可能没用。

With the first declaration, you can modify the characters of the array, but you can't change its size, and you can't make str1 refer to a different array.

使用第一个声明,您可以修改数组的字符,但不能更改其大小,并且不能使str1引用不同的数组。

With the second declaration, you can't modify the characters of the array, but you can change the pointer value itself so it points to some other array, or to nothing if you do str2 = NULL;.

使用第二个声明,您不能修改数组的字符,但您可以更改指针值本身,使其指向其他数组,如果您执行str2 = NULL,则不会改为任何内容。

If all you want to do with str1 or str2 is pass it to something that expects a char* that points to a string, you can use either form. The pointer form makes it a bit clearer that you're not going to be modifying the string. You can even write:

如果你想用str1或str2做的只是将它传递给需要指向字符串的char *的东西,你可以使用任何一种形式。指针形式使您更加清楚,您不会修改字符串。你甚至可以写:

const char *const str2 = "World";

if you want to prevent modifying either the string or the pointer.

如果你想阻止修改字符串或指针。

If you want to do something else, one form or the other may have some advantages, but I can't comment further without knowing what you're using it for.

如果你想做别的事情,一种形式或另一种形式可能有一些优势,但我不能在不知道你用它的情况下进一步评论。

There shouldn't be any significant difference in efficiency. Concentrate first on what how you want your code to behave. Adding const to anything you don't intend to modify helps document your intent and may help the compiler generate better code (because it doesn't need to assume that something may have been modified).

效率应该没有任何显着差异。首先关注您希望代码的行为方式。将const添加到您不打算修改的任何内容有助于记录您的意图,并可能有助于编译器生成更好的代码(因为它不需要假设某些内容可能已被修改)。

Recommended reading: the comp.lang.c FAQ, particularly section 6 which covers arrays and pointers.

推荐阅读:comp.lang.c FAQ,特别是第6节,其中包括数组和指针。


推荐阅读
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 本文由编程笔记#小编整理,主要介绍了关于数论相关的知识,包括数论的算法和百度百科的链接。文章还介绍了欧几里得算法、辗转相除法、gcd、lcm和扩展欧几里得算法的使用方法。此外,文章还提到了数论在求解不定方程、模线性方程和乘法逆元方面的应用。摘要长度:184字。 ... [详细]
  • Android自定义控件绘图篇之Paint函数大汇总
    本文介绍了Android自定义控件绘图篇中的Paint函数大汇总,包括重置画笔、设置颜色、设置透明度、设置样式、设置宽度、设置抗锯齿等功能。通过学习这些函数,可以更好地掌握Paint的用法。 ... [详细]
  • 本文介绍了Python语言程序设计中文件和数据格式化的操作,包括使用np.savetext保存文本文件,对文本文件和二进制文件进行统一的操作步骤,以及使用Numpy模块进行数据可视化编程的指南。同时还提供了一些关于Python的测试题。 ... [详细]
  • Introduction(简介)Forbeingapowerfulobject-orientedprogramminglanguage,Cisuseda ... [详细]
  • 判断数组是否全为0_连续子数组的最大和的解题思路及代码方法一_动态规划
    本文介绍了判断数组是否全为0以及求解连续子数组的最大和的解题思路及代码方法一,即动态规划。通过动态规划的方法,可以找出连续子数组的最大和,具体思路是尽量选择正数的部分,遇到负数则不选择进去,遇到正数则保留并继续考察。本文给出了状态定义和状态转移方程,并提供了具体的代码实现。 ... [详细]
  • iOS Swift中如何实现自动登录?
    本文介绍了在iOS Swift中如何实现自动登录的方法,包括使用故事板、SWRevealViewController等技术,以及解决用户注销后重新登录自动跳转到主页的问题。 ... [详细]
  • Whatsthedifferencebetweento_aandto_ary?to_a和to_ary有什么区别? ... [详细]
  • 本文讨论了微软的STL容器类是否线程安全。根据MSDN的回答,STL容器类包括vector、deque、list、queue、stack、priority_queue、valarray、map、hash_map、multimap、hash_multimap、set、hash_set、multiset、hash_multiset、basic_string和bitset。对于单个对象来说,多个线程同时读取是安全的。但如果一个线程正在写入一个对象,那么所有的读写操作都需要进行同步。 ... [详细]
  • 本文介绍了利用ARMA模型对平稳非白噪声序列进行建模的步骤及代码实现。首先对观察值序列进行样本自相关系数和样本偏自相关系数的计算,然后根据这些系数的性质选择适当的ARMA模型进行拟合,并估计模型中的位置参数。接着进行模型的有效性检验,如果不通过则重新选择模型再拟合,如果通过则进行模型优化。最后利用拟合模型预测序列的未来走势。文章还介绍了绘制时序图、平稳性检验、白噪声检验、确定ARMA阶数和预测未来走势的代码实现。 ... [详细]
author-avatar
M7y4C8r2a6z4y
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有