char a [] =?string?有什么区别?和char * p =?string?;? [英] What is the difference between char a[] = ?string?; and char *p = ?string?;?
问题描述
如标题所述,
之间的区别是什么? char a [] =?string?和
char * p =?string ?;
这个问题在面试中被问到我。
我甚至不理解语句。
char a [] =?string?
这里是?
它是一个字符串的一部分还是有一些特定的含义?
第一个是数组另一个是指针。 / p>
数组声明 char a [6];
请求留出六个字符的空格,名称 a
。也就是说,有一个名为 a
的位置,六个字符可以位于该位置。另一方面,指针声明 char * p;
请求一个保存指针的地方。指针可以通过名称 p
知道,并且可以指向任何地方的任何字符(或连续的字符数组)。
语句
char a [] =string
char * p =string;
会导致数据结构可以表示为:
+ --- + --- + --- + --- + --- + --- + ---- +
a: | s | t | r | i | n | g | \0 |
+ --- + --- + --- + --- + --- + --- + ---- +
+ ----- + + --- + --- + --- + --- + --- + --- + --- +
p:| * ======> | s | t | r | i | n | g | \0 |
+ ----- + + --- + --- + --- + --- + --- + --- + --- +
重要的是要意识到像 x [3]
是否 x
是一个数组或指针。给定上面的声明,当编译器看到表达式 a [3]
时,它会发出代码到 a
,移动三个元素通过它,并获取那里的字符。当它看到表达式 p [3]
时,它会发出代码到 p
在那里,向指针添加三个元素大小,最后获取指向的字符。在上面的例子中, a [3]
和 p [3]
恰好是字符 l
,但是编译器得到的不同。
资料来源: comp.lang.c常见问题清单·问题6.2
As the heading says, What is the difference between
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.
The array declaration char a[6];
requests that space for six characters be set aside, to be known by the name a
. That is, there is a location named a
at which six characters can sit. The pointer declaration char *p;
on the other hand, requests a place which holds a pointer. The pointer is to be known by the name p
, and can point to any char (or contiguous array of chars) anywhere.
The statements
char a[] = "string";
char *p = "string";
would result in data structures which could be represented like this:
+---+---+---+---+---+---+----+
a: | s | t | r | i | n | g | \0 |
+---+---+---+---+---+---+----+
+-----+ +---+---+---+---+---+---+---+
p: | *======> | s | t | r | i | n | g |\0 |
+-----+ +---+---+---+---+---+---+---+
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.
Source: comp.lang.c FAQ list · Question 6.2
这篇关于char a [] =?string?有什么区别?和char * p =?string?;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!