2012-12-22 69 views
-3

可能重复:
Pointer Arithmetic: ++*ptr or *ptr++?你能解释* ptr ++和*(++ ptr)之间的区别吗?

我不明白有什么区别?这里是一个实现的代码的例子*的ptr ++

#include <stdio.h> 
int my_array[] = {1,23,17,4,-5,100}; 
int *ptr; 
int main(void) 
{ 
int i; 
ptr = &my_array[0]; /* point our pointer to the first 
element of the array */ 
printf("\n\n"); 
for (i = 0; i < 6; i++) 
{ 
printf("my_array[%d] = %d ",i,my_array[i]); 
printf("ptr + %d = %d\n",i, *ptr++); 

} 
return 0; 
} 

输出是

my_array[0] = 1 ptr + 0 = 1 
my_array[1] = 23 ptr + 1 = 23 
my_array[2] = 17 ptr + 2 = 17 
my_array[3] = 4 ptr + 3 = 4 
my_array[4] = -5 ptr + 4 = -5 
my_array[5] = 100 ptr + 5 = 100 

当改变第二printf语句给printf( “PTR +%d =%d \ n” 个,我,*(++ ptr)); 这成为输出继电器:

my_array[0] = 1 ptr + 0 = 23 
my_array[1] = 23 ptr + 1 = 17 
my_array[2] = 17 ptr + 2 = 4 
my_array[3] = 4 ptr + 3 = -5 
my_array[4] = -5 ptr + 4 = 100 
my_array[5] = 100 ptr + 5 = -1881141248 

有人请详细解释的差异,所以我能理解。

+1

'* ++ ptr'增量,然后返回* current * eval,'* ptr ++'增量,然后返回* prior * eval。这是涵盖了一些[问题](http://stackoverflow.com/questions/5209602/pointer-arithmetic-ptr-or-ptr)和[答案](http://stackoverflow.com/questions/13338730/ vs-precedence-in-c/13338801#13338801),仅举几例。 – WhozCraig

回答

3

一个递增指针BEFORE提取它指向​​的内容,另一个增量从指针提取后。

在第二个例子,你已加强你过去的数组的最后一次迭代的结束,要打印(可能)的指针是在存储位置阵列后立即(或一些随机的垃圾)

1

一个是预增加运算符,另一个是后增加运算符。

printf("%d", i++);是一样的:

printf("%d", i); 
i += 1; 

虽然printf("%d", ++i);是一样的:

i += 1; 
printf("%d", i); 
3

这代表没有一个给予好评的机会,因为这个问题是关于无论如何都要关闭,但我无论如何,我不得不把它放在这里。

当使用*ptr++会发生以下情况:

  1. 使由式宽度的字节ptr
  2. 现有的值递增ptr的副本(在本例之一,因为char是一个字节)
  3. 推测之前值来自(1)中制作的副本

当使用*++ptr会发生以下情况:

  1. 增量ptr通过型宽度字节(在此情况下,一个,由于char是一个字节)
  2. 解除引用ptr'的新值。

在C++对象上重写上述操作符时,后递增的基本复制然后递增要求对于性能至关重要,因为临时复制可能非常昂贵。


后递增

下面演示后增量行为任何人怀疑这一点:

#include <stdio.h> 
#include <stdlib.h> 
#include <stdarg.h> 

static char test[] = "AB"; 
static const char *ptr = test; 

void myprintf(const char *fmt, ...) 
{ 
    va_list args; 
    va_start(args, fmt); 
    printf("myprintf: %c\n", *ptr); 
    vprintf(fmt, args); 
} 

int main(int argc, char *argv[]) 
{ 
    myprintf("main: %c\n", *ptr++); 
    return EXIT_SUCCESS; 
} 

输出

myprintf: B 
main: A 

无在调用myprintf()之前,ptr的值已经增加了main(),这与大多数人的想法相反,并且与大多数C/C++教师和书籍显然教导相反。这方面的一个拆卸证明这是这种情况:

movq _ptr(%rip), %rsi  ; ptr value moved into rsi 
movq %rsi, %rcx   ; ptr value moved into rcx 
addq $1, %rcx    ; increment value by one 
movq %rcx, _ptr(%rip)  ; ** store incremented address back into ptr ** 
movsbl (%rsi), %esi   ; old pointer value still in rsi dereferenced here. 
movq %rax, %rdi   
movb $0, %al    
callq _myprintf 
movl $0, %eax 

预递增

上述相同的代码,但使用前递增,这意味着变化main()此单个呼叫:

myprintf("main: %c\n", *++ptr); 

输出

myprintf: B 
main: B 
相关问题