在C中,我可以初始化一个指针声明字符串以同样的方式,我可以初始化字符数组声明中的字符串? [英] In C, can I initialize a string in a pointer declaration the same way I can initialize a string in a char array declaration?

查看:99
本文介绍了在C中,我可以初始化一个指针声明字符串以同样的方式,我可以初始化字符数组声明中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做code的这两条线达到同样的效果?如果我有一个功能,这些线是存储在这两种情况下栈上的字符串?是否有一个强有力的理由,为什么我应该使用一个比其他,除了不需要申报空终止于code的第一行?

 个char [] =字符串;
的char * s =字符串\\ 0;


解决方案

没有,这两条线没有达到同样的效果。

个char [] =串结果的7个字节的修改阵列,最初充满含量的'' T''R''我''N''G''\\ 0'(全部来自运行复制字串文本)。

的char * s =字符串导致一个指向一些的只读的包含字符串字面串的记忆。

如果你想修改字符串的内容,那么第一个是唯一的出路。如果你只需要只读访问字符串,则第二个会稍微快一点,因为字符串没有被复制。


在这两种情况下,没有必要以指定字符串的空终止。当它遇到闭幕的编译器会照顾你们。

Do these two lines of code achieve the same result? If I had these lines in a function, is the string stored on the stack in both cases? Is there a strong reason why I should use one over the other, aside from not needing to declare the null terminator in the first line of code?

char  s[] = "string";
char* s   = "string\0";

解决方案

No, those two lines do not achieve the same result.

char s[] = "string" results in a modifiable array of 7 bytes, which is initially filled with the content 's' 't' 'r' 'i' 'n' 'g' '\0' (all copied over at runtime from the string-literal).

char *s = "string" results in a pointer to some read-only memory containing the string-literal "string".

If you want to modify the contents of your string, then the first is the only way to go. If you only need read-only access to a string, then the second one will be slightly faster because the string does not have to be copied.


In both cases, there is no need to specify a null terminator in the string literal. The compiler will take care of that for you when it encounters the closing ".

这篇关于在C中,我可以初始化一个指针声明字符串以同样的方式,我可以初始化字符数组声明中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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