为什么 post 通过指针变量 (*variablePointer++) returns 增加一个变量的值是垃圾值?
Why post increment to value of a variable by pointer variable (*variablePointer++) returns garbage value?
我只是在玩 pre/post increment/decrement C
语言。在下面的程序中,变量 var
一切正常。但是指针变量自增*varAddress++
return垃圾值
#include <stdio.h>
int main(int argc, const char * argv[])
{
int var = 1;
int *varAddress = &var;
printf("Value befor pre increment %d\n",*varAddress);
++*varAddress;
printf("Value after pre increment %d\n",*varAddress);
printf("Value befor post increment %d\n",*varAddress);
*varAddress++;
printf("Value after post increment %d\n",*varAddress);
return 0;
}
输出
Value befor pre increment 1
Value after pre increment 2
Value befor post increment 2
Value after post increment 1606416400
Program ended with exit code: 0
++
的优先级高于 *
因此通过执行 *varAddress++
您将指针移动到某个无主位置并尝试取消引用它,这将导致未定义的行为.
根据Operator Precedence,后缀自增的优先级高于间接运算符,所以*varAddress++
等价于:
*(varAddress++);
这将增加指针本身,然后指向其他地方未分配的内存,这就是为什么 *varAddress
将 return 垃圾值(这是 UB)。
您可能想要:
(*varAddress)++;
#include<stdio.h>
void main(){
char arr[] ="abcd";
char *p=arr,*q=arr;
char k,temp;
temp = *p++; /* here first it assigns value present in address which
is hold by p and then p points to next address.*/
k = ++*q;/*here increments the value present in address which is
hold by q and assigns to k and also stores the incremented value in the same
address location. that why *q will get 'h'.*/
printf("k is %c\n",k); //output: k is h
printf("temp is %c\n",temp);//output: temp is g
printf("*p is %c\n",*p);//output: *p is e
printf("*q is %c",*q);//output: *q is h
}
我只是在玩 pre/post increment/decrement C
语言。在下面的程序中,变量 var
一切正常。但是指针变量自增*varAddress++
return垃圾值
#include <stdio.h>
int main(int argc, const char * argv[])
{
int var = 1;
int *varAddress = &var;
printf("Value befor pre increment %d\n",*varAddress);
++*varAddress;
printf("Value after pre increment %d\n",*varAddress);
printf("Value befor post increment %d\n",*varAddress);
*varAddress++;
printf("Value after post increment %d\n",*varAddress);
return 0;
}
输出
Value befor pre increment 1
Value after pre increment 2
Value befor post increment 2
Value after post increment 1606416400
Program ended with exit code: 0
++
的优先级高于 *
因此通过执行 *varAddress++
您将指针移动到某个无主位置并尝试取消引用它,这将导致未定义的行为.
根据Operator Precedence,后缀自增的优先级高于间接运算符,所以*varAddress++
等价于:
*(varAddress++);
这将增加指针本身,然后指向其他地方未分配的内存,这就是为什么 *varAddress
将 return 垃圾值(这是 UB)。
您可能想要:
(*varAddress)++;
#include<stdio.h>
void main(){
char arr[] ="abcd";
char *p=arr,*q=arr;
char k,temp;
temp = *p++; /* here first it assigns value present in address which
is hold by p and then p points to next address.*/
k = ++*q;/*here increments the value present in address which is
hold by q and assigns to k and also stores the incremented value in the same
address location. that why *q will get 'h'.*/
printf("k is %c\n",k); //output: k is h
printf("temp is %c\n",temp);//output: temp is g
printf("*p is %c\n",*p);//output: *p is e
printf("*q is %c",*q);//output: *q is h
}