如何增加指针地址和指针的值

如何增加指针地址和指针的值

本文介绍了如何增加指针地址和指针的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

让我们假设,

int *p;
int a = 100;
p = &a;

以下代码实际上会做什么以及如何做?

What will the following code actually do and how?

p++;
++p;
++*p;
++(*p);
++*(p);
*p++;
(*p)++;
*(p)++;
*++p;
*(++p);

我知道,这在编码方面有点混乱,但我想知道当我们这样编码时实际会发生什么.

I know, this is kind of messy in terms of coding, but I want to know what will actually happen when we code like this.

注意:假设a=5120300的地址存储在指针p中,其地址为3560200.现在,p & 的值是多少?一个在每个语句执行之后?

Note : Lets assume that the address of a=5120300, it is stored in pointer p whose address is 3560200. Now, what will be the value of p & a after the execution of each statement?

推荐答案

首先,++ 运算符优先于 * 运算符,而 () 运算符优先于其他所有内容.

First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.

第二,++number 运算符与 number++ 运算符相同,如果您没有将它们分配给任何东西.区别是number++先返回number再增加number,而++number先增加再返回.

Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.

第三,通过增加指针的值,您将其增加其内容的大小,也就是说,您正在增加它,就像您在数组中迭代一样.

Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.

总结一下:

ptr++;    // Pointer moves to the next int position (as if it was an array)
++ptr;    // Pointer moves to the next int position (as if it was an array)
++*ptr;   // The value pointed at by ptr is incremented
++(*ptr); // The value pointed at by ptr is incremented
++*(ptr); // The value pointed at by ptr is incremented
*ptr++;   // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value pointed at by ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr;   // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault

这里的案例比较多,可能有误,如有错误请指正.

As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.

所以我错了,优先级比我写的复杂一点,看这里:http://en.cppreference.com/w/cpp/language/operator_precedence

So I was wrong, the precedence is a little more complicated than what I wrote, view it here:http://en.cppreference.com/w/cpp/language/operator_precedence

这篇关于如何增加指针地址和指针的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:32