sharif1981
sharif1981

Reputation: 41

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. But so far I know char in C is 1 byte and int in array is 4 byte. So I can not understand how the increment operator behave here. Can anyone please explain it.

Upvotes: 0

Views: 227

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134276

As per the C11 standard document, chapter 6.5.2.5, Postfix increment and decrement operators

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).

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.


Now for your example,

  • chrArray is of type char *. So, if we do chrArray++, a value of the type char [sizeof(char), which is 1] will be added to chrArray as the result.

  • OTOH, intArray is of type int *. 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.

Basically, a Postfix increment operator on a pointer variable of any type points to the next element (provided, valid access) of that type.

Upvotes: 3

Amnon Shochot
Amnon Shochot

Reputation: 9356

This is handled by the compiler that knows the type of the pointer, thus can increment the address it stores by the relevant size, whether it is a char, an int or any other type.

Upvotes: 4

Related Questions