简体   繁体   English

指针增量减量语法差异

[英]Pointer Increment Decrement Syntax Difference

when I work on pointers on a website I stick at a point. 当我在网站上处理指针时,我会停留在某个位置。

When I write the given example I can assign adresses of array on a pointer for an increment a pointer example like ptr = arr; 当我写给定的例子时,我可以为一个指针分配一个数组地址,以增加一个指针的例子,例如ptr = arr; and it works correctly, but when I do the same thing for the decrement example it doesn't work it works only when I write like this ptr = &arr[2] . 并且它可以正常工作,但是当我对减量示例执行相同操作时,它不起作用,只有当我这样写ptr = &arr[2]时,它才起作用。 Why I have to write ampersand for decrement example? 为什么我必须写一个&符作为减量示例? what is the difference between those two? 两者有什么区别?

int main()
{
    int arr[3]={10,20,30};
    int *ptr,i;

    ptr=arr;

    for(i=0;i<3;i++)
    {
        printf("adress of variable arr[%d] %x\n",i+1,ptr);
        printf("value of arr[%d] = %d\n",i+1,*ptr);
        ptr++;
    }
    return 0;
}

You don't have to write it, just use the pointer: 您不必编写它,只需使用指针即可:

 ptr = var + 2 ;

for(i=0;i<3;i++)
{ 
    printf("%d" , *ptr ) ;
    ptr-- ;

Note that the last element is at +2 not +3. 请注意,最后一个元素位于+2而不是+3。

in case of an int arr[3] , &arr[0] and arr points to the same thing, the base address of the array, or, the address of the first element in the array. int arr[3]情况下, &arr[0]arr指向同一事物,即数组的基地址或数组中第一个元素的地址。 That's why in your increment case, you're allowed to write ptr = var which is nothing but storing the starting address in a separate pointer. 这就是为什么在增量情况下,您可以写ptr = var ,只不过将起始地址存储在单独的指针中。

In case of decrements, there is nothing which can point directly to the end-of-array element address. 在递减的情况下,没有什么可以直接指向数组末尾元素地址。 So , you have to use the address-of-last-element [ &arr[n-1] , n being the size] to denote the address of the last element. 因此,您必须使用address-of-last-element [ &arr[n-1]n为大小]来表示最后一个元素的地址。

The difference is that in "decrement" case you use [] . 区别在于,在“减量”情况下,您使用[] Think of arr as reference to whole array thus it is ok (compiler wise) to do ptr=arr or ptr=&arr with same result. arr视为对整个数组的引用,因此可以以相同的结果执行ptr=arrptr=&arr (在编译器方面)。 On the other hand arr[3] is a reference to object in array, so you need to get its address explicitly (no compiler optimization for you). 另一方面, arr[3]是对数组中对象的引用,因此您需要显式获取其地址(没有针对您的编译器优化)。

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

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