简体   繁体   English

* argv ++和* argv之间的差异-达到限制时

[英]Difference between *argv++ and *argv— when reaching the limit

could someone explain why 有人可以解释为什么

int main(int argc, const char * argv[]) {
  while (* argv) 
    puts(* argv++);
  return 0 ;
}

is legal, and 是合法的,并且

int main(int argc, const char * argv[]) {
  argv += argc - 1;
  while (* argv) 
    puts(* argv--);
  return 0 ;
}

isn't? 是不是? In both cases the 'crement inside the while loop will point outside of the bounds of argv. 在这两种情况下,while循环内的增量都将指向argv的边界之外。 Why is it legal to point to an imaginary higher index, and not to an imaginary lower index? 为什么指向虚构的较高索引而不指向虚构的较低索引是合法的?

Best regards. 最好的祝福。

Because the C standard says you can form a pointer to one past the end of an array, and it will still compare properly to pointers into the array (though you can't dereference it). 因为C标准说您可以形成一个指向数组末尾的指针,并且它仍然可以与数组中的指针进行正确比较(尽管您不能取消引用它)。

The standard does not say anything of the sort for a pointer to an address before the beginning of an array -- even forming such a pointer gives undefined behavior. 该标准没有对数组开头之前指向地址的指针进行任何说明,即使形成这样的指针也会产生不确定的行为。

Loop semantics and half-open intervals. 循环语义和半开间隔。 The idiomatic way for iterating through an array or list of objects pointed to by a pointer is: 遍历指针所指向的对象的数组或列表的惯用方式是:

for (T *p = array; p < array + count; p++)

Here, p ends up being out-of-bounds (off by one, pointing one past the end of the array), so it's (not only conceptually) useful to require this not to invoke undefined behavior (the Standard actually imposes this requirement). 在这里, p最终越界(偏离一,指向数组末尾一个),因此(不仅仅在概念上)要求不调用未定义的行为是有用的(标准实际上强加了此要求) 。

The standard forces argv[argc] to be equal to NULL , so dereferencing argv when it's been incremented argc times is legal. 该标准强制argv[argc]等于NULL ,因此在增加argc次数后取消引用argv是合法的。

On the other hand nothing is defined about the address preceding argv , so argv - 1 could be anything. 在另一方面没有被定义约前的地址argv ,所以argv - 1可以是任何东西。

Note that argv is the only array of strings guaranteed to behave this way, as far as I know. 请注意,据我所知,argv是唯一保证以这种方式运行的字符串数组。

From the standard: 从标准:

5.1.2.2.1 Program Startup 5.1.2.2.1程序启动

If they are declared, the parameters to the main function shall obey the following costraints: 如果声明了它们,则主函数的参数应遵循以下要求:

argv[argc] shall be a null pointer argv [argc]应为空指针

argv++ or ++argv as it is const pointer. argv++++argv是常量指针。

If you take a simple array like char* arr[10] and try arr++ it will give error 如果采用像char* arr[10]这样的简单数组并尝试使用arr++ ,它将给出错误信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM