C:字符指针和数组的区别 [英] C: differences between char pointer and array

查看:36
本文介绍了C:字符指针和数组的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

char amessage[] = "now is the time";
char *pmessage = "now is the time";

我从 The C Programming Language, 2nd Edition 中读到,上述两个语句没有做同样的事情.

I read from The C Programming Language, 2nd Edition that the above two statements don't do the same thing.

我一直认为数组是一种操作指针以存储一些数据的便捷方式,但显然事实并非如此……C 中数组和指针之间的非平凡"区别是什么?

I always thought that an array is an convenient way to manipulate pointers to store some data, but this is clearly not the case... What are the "non-trivial" differences between arrays and pointers in C?

推荐答案

没错,但这是一个细微的差别.本质上,前者:

True, but it's a subtle difference. Essentially, the former:

char amessage[] = "now is the time";

定义一个数组,其成员位于当前作用域的堆栈空间中,而:

Defines an array whose members live in the current scope's stack space, whereas:

char *pmessage = "now is the time";

定义一个指针,它位于当前作用域的堆栈空间中,但它引用了别处的内存(在这个指针中,现在是时间"存储在内存中的别处,通常是一个字符串表).

Defines a pointer that lives in the current scope's stack space, but that references memory elsewhere (in this one, "now is the time" is stored elsewhere in memory, commonly a string table).

另外,请注意,因为属于第二个定义(显式指针)的数据未存储在当前作用域的堆栈空间中,因此未指定确切的存储位置,不应修改.

Also, note that because the data belonging to the second definition (the explicit pointer) is not stored in the current scope's stack space, it is unspecified exactly where it will be stored and should not be modified.

正如 Mark、GMan 和 Pavel 所指出的,当地址运算符用于这些变量中的任何一个时,也存在差异.例如,&pmessage 返回一个 char** 类型的指针,或一个指向 chars 的指针,而 &amessage 返回一个 char(*)[16] 类型的指针,或一个指向 16 个字符的数组的指针(它就像一个字符**,需要像 litb 指出的那样被取消引用两次).

As pointed out by Mark, GMan, and Pavel, there is also a difference when the address-of operator is used on either of these variables. For instance, &pmessage returns a pointer of type char**, or a pointer to a pointer to chars, whereas &amessage returns a pointer of type char(*)[16], or a pointer to an array of 16 chars (which, like a char**, needs to be dereferenced twice as litb points out).

这篇关于C:字符指针和数组的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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