C中的* ptr + = 1和* ptr ++之间的区别 [英] Difference between *ptr += 1 and *ptr++ in C
问题描述
我刚刚开始研究C,在做一个有关将指针传递给指针作为函数参数的示例时,我发现了一个问题.
I just started to study C, and when doing one example about passing pointer to pointer as a function's parameter, I found a problem.
这是我的示例代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int* allocateIntArray(int* ptr, int size){
if (ptr != NULL){
for (int i = 0; i < size; i++){
ptr[i] = i;
}
}
return ptr;
}
void increasePointer(int** ptr){
if (ptr != NULL){
*ptr += 1; /* <----------------------------- This is line 16 */
}
}
int main()
{
int* p1 = (int*)malloc(sizeof(int)* 10);
allocateIntArray(p1, 10);
for (int i = 0; i < 10; i++){
printf("%d\n", p1[i]);
}
increasePointer(&p1);
printf("%d\n", *p1);
p1--;
free(p1);
fgets(string, sizeof(string), stdin);
return 0;
}
当我将*ptr+=1
修改为*ptr++
时,问题发生在第16行.预期的结果应该是整个数组和数字1,但是当我使用*ptr++
时,结果是0.
The problem occurs in line 16, when I modify *ptr+=1
to *ptr++
. The expected result should be the whole array and number 1 but when I use *ptr++
the result is 0.
+=1
和++
之间是否有区别?我以为他们都是一样的.
Is there any diffirence between +=1
and ++
? I thought that both of them are the same.
推荐答案
差异是由于运算符优先级造成的.
The difference is due to operator precedence.
后递增运算符++
的优先级高于取消引用运算符*
的优先级.因此*ptr++
等效于*(ptr++)
.换句话说,后置增量会修改指针,而不是其指向的指针.
The post-increment operator ++
has higher precedence than the dereference operator *
. So *ptr++
is equivalent to *(ptr++)
. In other words, the post increment modifies the pointer, not what it points to.
赋值运算符+=
的优先级比取消引用运算符*
的优先级低,因此*ptr+=1
等效于(*ptr)+=1
.换句话说,赋值运算符修改指针指向的值,并且不更改指针本身.
The assignment operator +=
has lower precedence than the dereference operator *
, so *ptr+=1
is equivalent to (*ptr)+=1
. In other words, the assignment operator modifies the value that the pointer points to, and does not change the pointer itself.
这篇关于C中的* ptr + = 1和* ptr ++之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!