what is the diference of p++ and ++p
时间: 2024-09-21 14:09:35 浏览: 38
In C programming, both `p++` and `++p` are increment operators used to increase the value of a pointer by one. However, there's a subtle difference in how they operate:
1. `p++`: This is called the post-increment operator. When you use `p++`, the current value of the pointer (`p`) is incremented first, and then the new value (which has increased) is used for any subsequent operation. In other words, if `p` initially points to an address, after `p++`, the memory location pointed to by `p` will be incremented, and `p` itself will still point to the original address before the increment.
Example usage:
```c
int arr[] = {1, 2, 3};
int *p = arr;
printf("%d, ", *p); // prints 1
p++;
printf("%d\n", *p); // prints 2, here p now points to the second element
```
2. `++p`: The pre-increment operator increments the pointer and then returns the updated value. So when you write `++p`, it increases the pointer and assigns the new value back to `p`. If you try to dereference `p` immediately after this operation, it will access the next element.
Example usage:
```c
int arr[] = {1, 2, 3};
int *p = arr;
printf("%d, ", *p); // prints 1
++p; // increments p and now points to the second element
printf("%d\n", *p); // also prints 2, as p has already been incremented
```
Both forms achieve the same end result of advancing the pointer, but the choice between them may depend on your specific use case and whether you need the incremented value or just want to modify the pointer directly. For example, when you're iterating through an array, using `++p` can make the code more readable since you don't have to dereference the pointer twice consecutively.
阅读全文