简体   繁体   English

C - “char var []”和“char * var”之间的区别?

[英]C - Difference between “char var[]” and “char *var”?

I am expecting that both following vectors have the same representation in RAM: 我期待以下两个向量在RAM中具有相同的表示:

char a_var[] = "XXX\x00";
char *p_var  = "XXX";

But strange, a call to a library function of type f(char argument[]) crushs the running application if I call it using f(p_var) . 但奇怪的是,如果我使用f(p_var)调用它,则调用类型为f(char argument[])的库函数会破坏正在运行的应用程序。 But using f(a_var) is Ok! 但是使用f(a_var)就可以了!

Why? 为什么?

The first creates an array of char containing the string. 第一个创建包含字符串的char数组。 The contents of the array can be modified. 可以修改数组的内容。 The second creates a character pointer which points to a string literal. 第二个创建一个指向字符串文字的字符指针。 String literals cannot be modified. 字符串文字无法修改。

在猜测时,函数f修改传递给它的字符串的内容。

As others said, char *p_var = "XXX"; 正如其他人所说, char *p_var = "XXX"; creates a pointer to a string literal that can't be changed, so compiler implementations are free to reuse literals, for example: 创建一个指向无法更改的字符串文字的指针,因此编译器实现可以自由地重用文字,例如:

char *p_var  = "XXX";
char *other  = "XXX";

A compiler could choose to optimize this by storing "XXX" only once in memory and making both pointers point to it, modifying their value could lead to unexpected behavior, so that's why you should not try to modify their contents. 编译器可以选择通过在内存中只存储一次“XXX”并使两个指针指向它来优化它,修改它们的值可能会导致意外行为,这就是为什么你不应该尝试修改它们的内容。

Arrays can be treated (generally) as pointers but that doesn't mean that they are always interchangeable. 数组可以(通常)作为指针处理,但这并不意味着它们总是可以互换的。 As the other said, your p_var points to a literal, something static that cannot be changed. 正如另一个所说,你的p_var指向一个文字,一些无法改变的静态。 It can point to something else (eg p_var = &a_var[0]) but you can't change the original value that you specified by quotes.... 它可以指向别的东西(例如p_var =&a_var [0]),但是你不能改变你用引号指定的原始值....

A similar problem is when you are define a variable as an array in one file, and then extern-use it as a pointer. 类似的问题是当您将变量定义为一个文件中的数组,然后extern-将其用作指针。

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM