You are on page 1of 13

Pointers in C

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?
int main() Three MLs have been
{ allocated. The first ML
int x = 16; holds int value. The
float y = 2.3; second ML holds
char z = 70; floating-point number.
. The last ML holds one
. byte integer.
.
}

Sometimes we say: the content of ……… is ……….


Run this code 
int main()
{
float num = 1.0;

printf(“num = %d\n”, num);


}
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
• 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 
int main()
{
float num = 1.0;

printf(“Address of num is %u\n”, &num);


}
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
Assume ptr is a pointer variable and x is an integer variable

x 10

ptr &x

Now ptr can access the value of x.

x = 10 HOW!!!!

Write: *variable . For example:


ptr = &x
printf(“%d\n”, *ptr);

Can you tell me why we put %d????


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
• To declare ptr as an integer pointer:
int *ptr;
• To declare ptr as a character pointer:
char *ptr;
Run this code
int main()
{
int x;
int *ptr;

x = 10;
ptr = &x;
*ptr = *ptr + 1;
printf(“x = %d\n”, x);
}
What is Asterisk ( * )?

char *z = *x*y;
!!?*&%^z*int-xy

You might also like