91-9990449935 0120-4256464 |
Pointer Arithmetic in CIn C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:
Incrementing Pointer in CIncrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location. Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below: 32 bitFor 32 bit int variable, it will increment to 2 byte. 64 bitFor 64 bit int variable, it will increment to 4 byte. Let's see the example of incrementing pointer variable on 64 bit OS. OutputAddress of p variable is 3214864300 After increment: Address of p variable is 3214864304 Decrementing Pointer in CLike increment, we can decrement a pointer variable. The formula of decrementing pointer is given below: 32 bitFor 32 bit int variable, it will decrement to 2 byte. 64 bitFor 64 bit int variable, it will decrement to 4 byte. Let's see the example of decrementing pointer variable on 64 bit OS. OutputAddress of p variable is 3214864300 After decrement: Address of p variable is 3214864296 C Pointer AdditionWe can add a value to the pointer variable. The formula of adding value to pointer is given below: 32 bitFor 32 bit int variable, it will add 2 * number. 64 bitFor 64 bit int variable, it will add 4 * number. Let's see the example of adding value to pointer variable on 64 bit OS. OutputAddress of p variable is 3214864300 After adding 3: Address of p variable is 3214864312 As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS. C Pointer SubtractionLike pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below: 32 bitFor 32 bit int variable, it will subtract 2 * number. 64 bitFor 64 bit int variable, it will subtract 4 * number. Let's see the example of subtracting value from pointer variable on 64 bit OS. OutputAddress of p variable is 3214864300 After subtracting 3: Address of p variable is 3214864288 You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.
Next TopicDynamic Memory Allocation in C
|