Friday, January 20, 2017  # Expressions of Pointers and Scale Factor in C

Last Update:

#### Expressions of Pointers:

We know it can express multiple variable by using arithmetic operator into a equation and we also did it before many time to calculate in program.
Example: If `x, y` and `sum` be `float` type variable then the statement of addition between x and y and assigning this result to another variable sum will be
``````float x, y, sum;
sum = x + y;``````

Similarly, we can do it with pointers but not with pointers variable. The following statement is valid.
``````float var_one, var_two, *a, *b, sum;
var_one = 10, var_two = 20;
a = &var_one, b = &var_two;
sum = *a + *b; ``````
Focus on fourth line. Similarly, we can express this for subtraction, multiplication, division. Remember for  division, space from division operator is major important. Otherwise, this statement will be adopted as comment section by compiler and it will show error.

Son don't code like below:
`division = *a /*b;  ` instead of
`division = *a / *b;` The following segment of code isn't valid.
``````float var_one, var_two, *a, *b, sum;
var_one = 10, var_two = 20;
a = &var_one, b = &var_two;
sum = a + b;``````
Focus on fourth line. It isn't permitted to operate between two pointer variable. So this statement isn't valid.
But it is permitted to increase or decrease a pointer variable as permitted for pointers. So the following statements are valid for the above code.
``````
sum = a++;
sum = sum + *b;``````

### Scale Factor

What will be happened if we increase or decrease or add or subtract with pointer variable? Suppose if we do increment an integer type pointer variable, the value of address of pointer variable will be increased with 4 or 2 (it will depend on system. You can check on your program by `sizeof()` function.) not 1. And this length of data type is called scale factor. To check this run the following code.
``````#include <stdio.h>
int main()
{
int var, *ptr;
ptr = &var;
printf("Length of integer data type: %d\n",sizeof(int));
printf("The address of ptr before increment: %u\n",ptr);
++ptr;
printf("The address of ptr after increment: %u\n",ptr)
} ``````
If the address of pointer variable be 4000 before increment, after increment it will be 4004 or 4002. For constant 1 it will be 4, for constant 2 it will be 3X4 and similarly will go on.
This code for integer data type. You can change this for float, double, char data type.
Question for test:
1. Is it valid to operate two pointer variable by arithmetic operator?
2. Can we add a pointer variable with number constant?
3. Is it same the scale factor for all system?

Next:
Previous: Declaration and Initialization of Chain of Pointer Elliyas Ahmed

Hi, I am Elliyas Ahmed, the founder of COMPROMATH. I try to share what I learn.

Work With Me - My Premium Services