C:字符指针和阵列之间的差异 [英] C: differences between char pointer and array

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

问题描述

考虑:

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

我从 C程序设计语言,第二版,上面的两个语句不做同样的事情读取。

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.

编辑:如由马克,GMAN,和Pavel指出,也有当操作者的地址,是在任一这些变量的使用的差异。例如,&安培; pmessage返回char类型的指针**,或者指针指向字符,而与放大器; amessage返回类型char(*)[16],或指针的指针指向16个字符数组(其中,像一个char **,需要两次解除引用作为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天全站免登陆