Pointers in C : Pointers in C What is a variable? : What is a variable? Each variable must be defined before you can use it inside your program.
Did you ask yourself why we have to declare variables?
First reason is To allocate memory
Second reason is Instruct compiler how
to treat this memory
location ML? As int or
float... What is a variable? : What is a variable? int main()
int x = 16;
float y = 2.3;
char z = 70;
} Three MLs have been allocated. The first ML holds int value. The second ML holds floating-point number. The last ML holds one byte integer. Sometimes we say: the content of ……… is ………. Run this code ? : Run this code ? int main()
float num = 1.0;
printf(“num = %d\n”, num);
} What is a variable? : What is a variable? A variable is a named memory location.
Variables provide direct access to its memory location.
Can you understand what will happen when you write:
x = 44;
y = x; Memory Addresses : Memory Addresses Each ML has an address ? each variable has an address.
Memory address in 32-bit Machines is 32-bit unsigned integer number.
How to get the address of a variable?
&variable_name Run this code ? : Run this code ? int main()
float num = 1.0;
printf(“Address of num is %u\n”, &num);
} Pointer Variables : Pointer Variables Ask yourself:
What is an integer variable?
What is a floating-point variable?
What is a character variable?
Now, what is a pointer variable?
I will answer: is a variable which holds an address of a ML. Pointer Variable : Pointer Variable Assume ptr is a pointer variable and x is an integer variable x x = 10 10 ptr = &x &x Now ptr can access the value of x.
Write: *variable . For example:
Can you tell me why we put %d???? Declaring a Pointer Variable : Declaring a Pointer Variable In previous example, ptr points to the variable x. We say that ptr is an integer pointer.
Similarly, we have character pointer, floating pointer, long pointer, … . Declaring a Pointer Variable : Declaring a Pointer Variable To declare ptr as an integer pointer:
To declare ptr as a character pointer:
char *ptr; Run this code : Run this code int main()
x = 10;
ptr = &x;
*ptr = *ptr + 1;
printf(“x = %d\n”, x);
} What is Asterisk ( * )? : What is Asterisk ( * )? char *z = *x*y;