Introduction to Pointers
- When data is stores in the memory it will be stored in one or more bytes of memory. When the data is stored in more than one byte of memory, it occupies continuous memory.
- It is a derive data type in C. Pointer returns the value of stored address.
- “A pointer is a variable which contains the address in memory of another variable.”
- Within the computer’s memory, every stored data item occupies one or more contiguous memory cells.
- The number of memory cells required to store a data item depends on the type of the data item.
- For example, a single character will typically be stored in one byte of memory, an integer usually requires two contiguous bytes, a floating-point number usually requires four contiguous bytes, and a double precision usually requires eight contiguous bytes.
- Diagram illustrates the idea of pointers. As you can see below; Yptr is pointing to memory address 100.
Advantages of pointers
- Pointer can be used to pass information back & forth between a function & its reference point.
- Pointers also permit references to other function to be specified as argument to a given function.
- Pointers are closely associated with arrays & therefore provide an alternate way to access individual array elements.
- Pointers provide a convenient way to represent multi-dimensional array to be replayed by a lower dimensional array of pointer.
- Pointer variables, like all other variables, must be declared before, they may be used in C program.
- When a pointer variable is declared, the variable name must be preceded by an asterisk (*). This identifies the fact that the variable is a pointer.
- The data type that appears in the declaration refers to the object of the pointer. i.e. the data item that is stored in the address represented by the pointer, rather than the pointer itself.
- Declaring pointers can be very confusing and difficult at times.
- The data type that appears in declaration of pointer variable will be the data type of the variable to which it points.
- Pointer can only point to variable of the same data type.
- Thus a pointer declaration may be written in general terms as :
Where ptr is the name of the pointer variable, and data-type refers to the data type of the pointer object.
Syntax:- Data type *ptr name;
Ex:- int *p;