简体   繁体   English

理解指针变量增量

[英]Understanding pointer variable increment

While reading about pointers I found a pointer variable is used to indicate an array like this:在阅读有关指针的内容时,我发现一个指针变量用于指示这样的数组:

char* chrArray;
int* intArray;

After that I found charArray++ and intArray++ used in code to indicate the next element of charArray and intArray .之后我发现在代码中使用charArray++intArray++来指示charArrayintArray的下一个元素。 But so far I know char in C is 1 byte and int in array is 4 byte.但到目前为止,我知道 C 中的char是 1 个字节,数组中的int是 4 个字节。 So I can not understand how the increment operator behave here.所以我无法理解增量运算符在这里的表现。 Can anyone please explain it.任何人都可以请解释一下。

这是由知道指针类型的编译器处理的,因此可以按相关大小增加它存储的地址,无论它是 char、int 还是任何其他类型。

As per the C11 standard document, chapter 6.5.2.5, Postfix increment and decrement operators根据C11标准文档,第 6.5.2.5 章,后缀自增和自减运算符

The result of the postfix ++ operator is the value of the operand.后缀++运算符的结果是操作数的值。 As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).作为副作用,操作数对象的值会增加(即,将适当类型值 1添加到其中)。

So, whenever you're using a postfix increment operator, you're not adding any specific value , rather, you're addding value 1 of the type of the operand on which the operator is used.因此,无论何时使用后缀递增运算符,都不会添加任何特定值,而是添加使用该运算符的操作数类型的值 1


Now for your example,现在以你的为例,

  • chrArray is of type char * . chrArraychar *类型。 So, if we do chrArray++ , a value of the type char [ sizeof(char) , which is 1 ] will be added to chrArray as the result.因此,如果我们执行chrArray++ ,则char [ sizeof(char) ,即1 ] 类型的值将作为结果添加到chrArray

  • OTOH, intArray is of type int * . OTOH, intArrayint *类型。 So, if we do intArray++ , a value of the type int [ sizeof(int) , which is 4 on 32 bit platform, may vary] will be added to intArray as the result.因此,如果我们执行intArray++ ,则int [ sizeof(int)类型的值,在 32 位平台上为4 ,可能会有所不同] 将作为结果添加到intArray

Basically, a Postfix increment operator on a pointer variable of any type points to the next element (provided, valid access) of that type.基本上,任何类型的指针变量上的后缀增量运算符都指向该类型的下一个元素(提供的有效访问)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM