5 Secrets of Blogger (Service) You Don't Know

Recent Posts

Expressions of Pointers and Scale Factor in C

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;
Pointer increment and scale factor in C

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);
     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?

Previous: Declaration and Initialization of Chain of Pointer

Looking for more effecive Course?

C Programming For Beginners by Udemy icon
$15 (Original $145)
30-Day Money-Back Guarantee
  • 6 hours on-demand video
  • 1 Article
  • 2 Supplemental Resources
  • Full lifetime access
  • Access on mobile and TV
  • Certificate of Completion