huy*_*yen 121 c pointers post-increment
我刚刚开始学习C,当做一个关于将指针作为函数的参数传递给指针的例子时,我发现了一个问题.
这是我的示例代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我修改*ptr+=1为第16行时出现问题*ptr++.预期的结果应该是整个数组和数字1,但是当我使用*ptr++结果时为0.
有没有之间的任何diffirence +=1和++?我以为他们俩都是一样的.
use*_*109 286
差异是由于运营商优先级.
后增量运算符的++优先级高于解除引用运算符*.所以*ptr++相当于*(ptr++).换句话说,后增量会修改指针,而不是它指向的内容.
赋值运算符的+=优先级低于取消引用运算符*,因此*ptr+=1相当于(*ptr)+=1.换句话说,赋值运算符会修改指针指向的值,而不会更改指针本身.
a + b / c
a + (b/c)
Run Code Online (Sandbox Code Playgroud)
让我们再来一次
*ptr += 1
(*ptr) += 1
Run Code Online (Sandbox Code Playgroud)
再一次
*ptr++
*(ptr++)
Run Code Online (Sandbox Code Playgroud)
*ptr += 1,我们增加指针所指向的变量的值.*ptr++,我们在完成整个语句(代码行)之后递增指针,并返回对指针所指向的变量的引用.后者允许您执行以下操作:
for(int i = 0; i < length; i++)
{
// Copy value from *src and store it in *dest
*dest++ = *src++;
// Keep in mind that the above is equivalent to
*(dest++) = *(src++);
}
Run Code Online (Sandbox Code Playgroud)
这是用于将src数组复制到另一个dest数组的常用方法.