问题描述
没有指导似乎真的澄清这件事,我已经意识到我真的,真的需要把它直。
我的意思是,你可以为一个char分配内存*变量,或者说的char [25]变量?有什么不同?或者有文字......不能被操纵?......所以如果你要分配一个固定的字符串变量。像如果stringVariable为NULL:stringVariable =thisIsALiteralIsItNotSoWtf
,那你怎么处理它
有人能以正视听吗?而在最后一种情况下,用文字,你怎么照顾空终止的?这真的只是弄乱我的。
编辑:真正的问题似乎是,我的理解是,你必须为了完成甚至简单的事情忙里忙外,这些不同的结构。例如,只有的char *
可作为一个参数或返回值传递,但只有的char []
可分配文字和修改。我觉得这是很明显,我们经常/总是需要能够做两件事,那就是我的缺陷是。
The lifetime of a malloc
-ed string is not limited by the scope of its declaration. In plain language, you can return malloc
-ed string from a function; you cannot do the same with char[25]
allocated in the automatic storage, because its memory will be reclaimed upon return from the function.
String literals cannot be manipulated in place, because they are allocated in read-only storage. You need to copy them into a modifiable space, such as static, automatic, or dynamic one, in order to manipulate them. This cannot be done:
char *str = "hello";
str[0] = 'H'; // <<== WRONG! This is undefined behavior.
This will work:
char str[] = "hello";
str[0] = 'H'; // <<=== This is OK
This works too:
char *str = malloc(6);
strcpy(str, "hello");
str[0] = 'H'; // <<=== This is OK too
C compiler takes care of null termination for you: all string literals have an extra character at the end, filled with \0
.
这篇关于如何字符串和字符数组用C的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!