为什么指向“一个过去”允许但是指向“之前的一个”不是 ? [英] Why pointer to "one past" is allowed but pointer to "one before" is not ?
问题描述
为什么一个指针允许指向一个位置,而不是指向阵列末尾的某个位置,而不是指向数组开头的一个位置?有什么理由为什么
前者比后来更有用?
Spiros Bousbouras
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?
Spiros Bousbouras
推荐答案
sp****@gmail.com 写道:
为什么一个指针允许指向一个阵列结束后的一个位置而不是指向数组开始之前的一个位置?是否有任何理由为什么
前者比后者更有用?
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?
考虑代码如
char * str = somestring;
while(* str ++){
...
}
str may结束了一个地方过了一些地方 - 很高兴允许。
Consider code such as
char *str = somestring;
while(*str++) {
...
}
str might end up one place past somestring - nice to allow that.
Nils O. Sel?sdal写道:
Nils O. Sel?sdal wrote:
sp****@gmail.com 写道:
为什么是指针允许指向一个位置过去阵列结束但不是指向阵列开始之前的一个位置?是否有任何理由为什么
前者比后者更有用?
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?
考虑代码如
char * str = somestring;
while( * str ++){
...
}
str可能会在某个地方结束一个地方 - 很高兴允许这样做。
Consider code such as
char *str = somestring;
while(*str++) {
...
}
str might end up one place past somestring - nice to allow that.
是的。我的问题是对立的原因。也不允许。
一个人可以像
一样容易(source> = beg_of_string)* dest ++ = * source--;
$例如,b $ b以反向方式复制字符串。
我的例子是否会引起未定义的行为?
Spiros Bousbouras
Yes it is. My question was why the "opposite" is not allowed too.
One could have just as easily something like
while (source >= beg_of_string) *dest++ = *source-- ;
to copy a string in reverse for example.
Does my example evoke undefined behaviour by the way ?
Spiros Bousbouras
sp****@gmail.com 写道:
sp****@gmail.com wrote:
为什么一个指针允许指向一个数组末尾的位置但不是指向数组开始之前的一个位置?
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ?
因为一个经过任何数组的指针只需要一个字节(因为
只需要虚拟成员的_first byte_的地址)
有效,而不是任何其他的),但是开头之前的指针
需要分配整个数组大小的内存空间
成员。鉴于数组成员可以是包含长双精度数组的结构数组的单个结构,这可能会耗费大量
地址空间,否则可能会被有益地使用。
Richard
Because a pointer one past any array need only take a single byte (since
only the address of the _first byte_ of the virtual member need be
valid, not any further ones), but a pointer one before the beginning
requires the assignment of memory space the size of an entire array
member. Given that the array member can be a humungous struct containing
arrays of structs of arrays of long doubles, this can cost a lot of
address space that could otherwise be gainfully employed.
Richard
这篇关于为什么指向“一个过去”允许但是指向“之前的一个”不是 ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!