为什么通过指针变量(* variablePointer ++)将增量值增加到变量值会返回垃圾值?

时间:2016-03-30 06:28:24

标签: c++ c pointers post-increment

我只是在C语言中播放前后递增/递减。在下面的程序中,一切都可以使用变量var。但是指针变量*varAddress++的增量会返回垃圾值。

#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

3 个答案:

答案 0 :(得分:4)

根据Operator Precedence,后缀增量的优先级高于间接运算符,因此*varAddress++等同于:

*(varAddress++);

这将增加指针本身,然后指向其他地方未分配的内存,这就是为什么*varAddress将返回垃圾值(这是UB)。

你可能想要:

(*varAddress)++;

答案 1 :(得分:2)

++的优先级高于*所以通过执行*varAddress++,您将指针移动到某个非拥有位置并尝试取消引用它,这将导致未定义的行为。< / p>

答案 2 :(得分:0)

#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
}