指標與指標地址

2022-08-05 12:30:21 字數 1681 閱讀 7607

int urn[size];

urn[0] = 100;

urn[1] = 200;

urn[2] = 300;

urn[3] = 400;

urn[4] = 500;

int *ptr1,*ptr2,*ptr3;

ptr1 = urn;

ptr2 = &urn[2];

printf("當前指標的值和地址 ");

printf("ptr1 = %p, *ptr1 = %d, &ptr1 = %p\n",ptr1,*ptr1,&ptr1);

ptr3 = ptr1 + 4;

printf("ptr1 + 4 = %p, *(ptr1+4) = %d\n",ptr1+4,*(ptr1+4));

ptr1++;

printf("ptr1++, ptr1 = %p, *ptr1 = %d, &ptr1 = %p\n",ptr1,*ptr1,&ptr1);

ptr2--;

printf("ptr2--, ptr2 = %p, *ptr2 = %d, &ptr2 = %p\n",ptr2,*ptr2,&ptr2);

--ptr1;

++ptr2;

printf("--ptr1,++ptr2, ptr1 = %p, *ptr1 = %d, ptr2 = %p, *ptr2 = %d\n",ptr1,*ptr1,ptr2,*ptr2);

printf("ptr2 - ptr1, ptr2 = %p, ptr1 = %p, ptr2 - ptr1 = %d",ptr2,ptr1,ptr2-ptr1);

printf("ptr3 = %p, ptr3 - 2 = %p\n",ptr3,ptr3-2);

ptr1 = 0x7fff5fbff820,    // ptr1 指標中保持的值是:0x7fff5fbff820,它是urn陣列的首地址。

*ptr1 = 100,        // ptr1 儲存的變數的值

&ptr1 = 0x7fff5fbff818   // ptr1 是指標型別的變數,它在記憶體中的地址是:0x7fff5fbff818

ptr1 + 4 = 0x7fff5fbff830, *(ptr1+4) = 500

ptr1++, ptr1 = 0x7fff5fbff824, *ptr1 = 200, &ptr1 = 0x7fff5fbff818

ptr2--, ptr2 = 0x7fff5fbff824, *ptr2 = 200, &ptr2 = 0x7fff5fbff810

--ptr1,++ptr2, ptr1 = 0x7fff5fbff820, *ptr1 = 100, ptr2 = 0x7fff5fbff828, *ptr2 = 300

ptr2 - ptr1, ptr2 = 0x7fff5fbff828, ptr1 = 0x7fff5fbff820, ptr2 - ptr1 = 2   // 說明ptr2 和ptr1之間有2個int的距離

ptr3 = 0x7fff5fbff830, ptr3 - 2 = 0x7fff5fbff828  // 指標減去整數,指標地址改變。