显示值和数组以及指针在运行以下代码后指向的位置

时间:2016-10-10 18:17:21

标签: c pointers

这里有一段关于更新指针的代码。我对使用它们感到很困惑。谁能帮助我更清楚地理解它?

int a[8] = {5, 7, 22, -5, 1, 13, 77, 55};
int *p, *q, i;
p = a;
q = &a[3];
//The comment is what I think for this example
*(++p) = 14;   //I don't know I should increment it first or change the
               //current pointed value. If I look at the answer, it shows 
               //pointer is increasing first which mean p points to a[1] 
               //and assign the value at a[1] to 14 
*q = (*p)++;   //After step 1, the p point to 1. Assign *p to *q and (*p)++                          
               //means value++, 14+1=15
p += 4;        //pointer increment 4
*p += 6;       //current p point to a[5] and value = value+6
*(q-3) = *p--; //*p-- means *(p--) which means pointer p move one previous
               // where a[4]. And assign 1 to  pointer q-3(location) but don't
               //change where q points to now

结果是a = {19 15 22 14 1 19 77 55} 和p指向值1,q指向值14.

另一个例子:

int a[] = {5, 15, 34, 54, 14, 2, 52, 72}; 
int *p = a, *q = &a[5];

*(p++) = *q – 1; //from the example above, I should say *(p++) means pointer
                 // p++ first and assign *q-1 = 1 to a[1] where p points to now but 
                 // looking at the answer, don't understand why a[0] = 1
*p = *(q-1); 
p = p + 2; 
(*p)++;

这个结果是a = {1,14,34,55,14,2,52,72}。

0 个答案:

没有答案