Define pointer and array. Explain the difference between them.
- A pointer is a variable that holds a memory address. This address is the location of another object (typically, a variable) in memory. That is, if one variable contains the address of another variable, the first variable is said to point to the second.
- A pointer declaration consists of a base type, an *, and the variable name.
- The general form of declaring a pointer variable is :
type *name;
- 'type' is the base type of the pointer and may be any valid type.
- 'name' is the name of pointer variable.
- The base type of the pointer defines what type of variables the pointer can point to.
-
Example :int i =5;
int *p; //declares p as pointer to integer
p = &i; // p is assigned the address of int variable i.
- An array is a collection of variables of the same type that are referred to through a common name. A specific array element is accessed by an index. In C++ arrays consist of contiguous memory location. The lowest memory address corresponds to first element and the highest to the last element of the array. Arrays could be single dimensional or multi dimensional. A string is most common example of an array. It is a single dimensional array of characters.
- The general form for declaring a single dimensional array is :
type var_name[size];
- 'type' is data type.
- 'var_name' is name given to the array variable.
- 'size' is size of the array;
-
Example :int a[10]; //declares an array of 10 integers.
- As we can see from the definitions, array and pointer are entirely two different concepts. Array is a collection of variables; whereas pointer stores address of other variables. At the same time, we can have a pointer pointing to an array and an array of pointer variables.