Pointers Inc

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 11

Pointers in

C
Pointer Definition
• Holds a data value that references a unit of
memory storage.
In other words:
• A variable that holds Memory Address

How do we declare a Pointer in


C?
ip
<data_type> *ptr1, *ptr2, … ;
0x123
e.g. int * ip; 4
Variable ip is a pointer that can
Address-of and Dereference
Operators
A pointer is nothing more than a box that contains a
value that is underneath some other box.
There are two basic operators for dealing with
pointers in C.
• One is the address-of operator ‘&’. If you give it a
box, it returns the value underneath it.
• The other operator is the dereference operator
‘*’. This does exactly the opposite thing. If you give it
a box, it takes the value inside that box, then goes
and finds the other box that has that value
underneath it.
Address-of and Dereference Operators

example
1: void main(void)
{
2: int num;
3: int *pNum;
4: num = 57;
5: pNum = &num;
6: *pNum = 23
7: printf(“%d\n”,
num);
8: return 0;
}
Assigning Addresses to
Pointers
• Pointer to single element
Format: ptr = &element;
• Pointer to first array element
Format: ptr = array;
• Pointer to array element x
Format: ptr = &array[x];
Working with Pointers in
C
int *a, *b; // Declare Pointers a and b
int n=10; // Declare and initialize n
a = &n; // Store the address of n in a
*a = 20; // Change the value of n
// via pointer a
• a = b; // Store the content of
// Pointer a in pointer b
another example
int i = 7; // Declare and initialize i

int *p = &i; //Declare and initialize


Pointer p

int j = 8; // Declare another variable j

p = &j; // Let p points to j

*p = 10; // Change the value via p


Now lets get more
serious
int *P; // Declare Pointer P of type
integer
P = (int *) 1234; // assign arbitrary
address to P
*P = 10; // Store value 10 in the
allocated // memory 1234
Dynamic Memory Allocation
• Allocating /De-allocating
memory at the run-time.
• malloc(), calloc() and free()

• void *malloc (size_in_bytes);


• void *calloc (no_of_slots,
size_of_each_slot_in_bytes);
• void free(address);
example
what does this complicated line do?:

You might also like