What is the difference between char a[] = ?string?; and char *p = ?string?;?(char a[] = ?string? 和有什么区别?和 char *p = ?string?;?)
问题描述
正如标题所说,
char a[] = ?string?; and
char *p = ?string?;
这个问题是在面试中问我的.我什至不明白这句话.
This question was asked to me in interview. I even dont understand the statement.
char a[] = ?string?
这里是什么 ?
运算符?它是字符串的一部分还是具有某些特定含义?
Here what is ?
operator? Is it a part of a string or it has some specific meaning?
推荐答案
第一个是数组,另一个是指针.
The first one is array the other is pointer.
数组声明char a[6];
要求留出六个字符的空间,以名称a
表示.也就是说,有一个名为 a
的位置,可以坐六个字符.另一方面,指针声明 char *p;
请求一个存放指针的地方.指针的名称为 p
,并且可以指向任何地方的任何字符(或连续的字符数组).
The array declaration
char a[6];
requests that space for six characters be set aside, to be known by the namea
. That is, there is a location nameda
at which six characters can sit. The pointer declarationchar *p;
on the other hand, requests a place which holds a pointer. The pointer is to be known by the namep
, and can point to any char (or contiguous array of chars) anywhere.
声明
char a[] = "string";
char *p = "string";
将导致可以这样表示的数据结构:
would result in data structures which could be represented like this:
+---+---+---+---+---+---+----+
a: | s | t | r | i | n | g | |
+---+---+---+---+---+---+----+
+-----+ +---+---+---+---+---+---+---+
p: | *======> | s | t | r | i | n | g | |
+-----+ +---+---+---+---+---+---+---+
认识到像 x[3]
这样的引用会根据 x
是数组还是指针生成不同的代码,这一点很重要.鉴于上面的声明,当编译器看到表达式 a[3]
时,它发出代码以从位置 a
开始,将三个元素移过它,然后获取字符那里.当它看到表达式 p[3]
时,它发出代码从位置 p
开始,在那里获取指针值,向指针添加三个元素大小,最后获取指向的字符.在上面的例子中,a[3]
和 p[3]
碰巧都是字符 l
,但编译器得到的结果不同.
It is important to realize that a reference like x[3]
generates different code depending on whether x
is an array or a pointer. Given the declarations above, when the compiler sees the expression a[3]
, it emits code to start at the location a
, move three elements past it, and fetch the character there. When it sees the expression p[3]
, it emits code to start at the location p
, fetch the pointer value there, add three element sizes to the pointer, and finally fetch the character pointed to. In the example above, both a[3]
and p[3]
happen to be the character l
, but the compiler gets there differently.
来源:comp.lang.c 常见问题列表·问题 6.2
这篇关于char a[] = ?string? 和有什么区别?和 char *p = ?string?;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!