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? e.g.

ip <data_type> *ptr1, *ptr2, … ;

int * ip; Variable ip is a pointer that can

0x123 4

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

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];

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

Working with Pointers in C

another example int i = 7;
Pointer p // Declare and initialize i //Declare and initialize

int *p = &i; int j = 8; p = &j; *p = 10;

// Declare another variable j // Let p points to j // Change the value via p

int *P;

Now lets get more serious

// Declare Pointer P of type // assign arbitrary

integer

P = (int *) 1234;
address to P

*P = 10;
allocated

// Store value 10 in the 1234 // memory

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?:

Sign up to vote on this title
UsefulNot useful