0

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
sharif1981
  • 41
  • 8
  • See [Pointer Arithmetic](http://stackoverflow.com/questions/394767/pointer-arithmetic) – Anto Jurković Apr 03 '15 at 08:11
  • 1
    There is no language that gives you more control over memory than C (other than assembly...). With that great control comes great responsibility to know what is stored in memory at any given location and how to handle the value. Pointers are just variables, but instead of holding what you think of as a normal value, pointers hold the memory address to where the value is stored. When you declare pointers like you did above, they hold nothing until you assign an address to them. The normal example is `int n = 5; int *p = &n;` Here `p` holds the address of `n` where the value `5` is stored. – David C. Rankin Apr 03 '15 at 08:28

2 Answers2

4

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.

Amnon Shochot
  • 8,998
  • 4
  • 24
  • 30
  • That means for char increment operator set the pointer to indicate the next byte in memory? And for integer it sets after 4 byte? – sharif1981 Apr 03 '15 at 08:12
  • Generally yes. However, it is important to understand that the ++ operator semantics for pointers is to increase the address by the size of the item pointed. This is handled by the compiler during the compilation of the program. – Amnon Shochot Apr 03 '15 at 08:14
3

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261