Unit III Pointers & Structures
Unit III Pointers & Structures
Unit III Pointers & Structures
POINTER DEFINITION
✓ A pointer is a variable that contains the address of a variable.
int xyz = 50;
Assign the address of xyz to a variable p
p is the pointer variable to xyz
p = &xyz;
POINTER AND ADDRESS
A pointer is a group of cells (often two or four) that can hold an address.
p = &c;
c is a char
p is a pointer that points to char c
Represent by,
If ip points to the integer x, then *ip can occur in any context where x could,
so *ip = *ip + 10; increments *ip by 10.
The unary operators * and & bind more tightly than arithmetic operators, so
the assignment y = *ip + 1 takes whatever ip points at, adds 1, and assigns the
result to y.
Pointers and Function Arguments
• As an argument, a pointer is passed instead of a variable and its address is
passed instead of its value.
• As a result, any change made by the function using the pointer is permanently
stored at the address of the passed variable. In C, this is referred to as call by
reference.
• The calling program to pass pointers to the values to be changed:
swap(&a, &b);
Since the operator & produces the address of a variable, &a is a pointer to a.
In swap itself, the parameters are declared as pointers, and the operands are
accessed indirectly through them.
Example:
void swap(int *px, int *py) /* interchange *px and *py */
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
POINTER AND FUNCTION
ARGUMENTS
POINTERS AND ARRAYS
✓ Any operation that can be achieved by array subscripting can also be done
with pointers.
✓ The pointer version will in general be faster but, at least to the uninitiated,
somewhat harder to understand.
The declaration,
int a[10];
defines an array of size 10, that is, a block of 10 consecutive objects named a[0],
a[1], ...,a[9].
in
Bit-fields
• In C, we can specify the size (in bits) of the structure and
union members.
• The idea of bit-field is to use memory efficiently when we
know that the value of a field or group of fields will never
exceed a limit or is within a small range.
• C Bit fields are used when the storage of our program is
limited.
Need of Bit Fields in C
• Reduces memory consumption.
• To make our program more efficient and flexible.
• Easy to Implement.