Lecture13 Pointers Array
Lecture13 Pointers Array
Lecture13 Pointers Array
Whenever we declare a variable, the system allocates memory location(s) to hold the
value of the variable.
• Since every byte in memory has a unique address, this location will also have its own
(unique) address.
Pointer
Consider the statement
int xyz = 50;
• This statement instructs the compiler to allocate a location for the integer variable xyz,
and put the value 50 in that location.
• Suppose that the address location chosen is 1380.
• During execution of the program, the system always associates the name xyz with the
address 1380.
• The value 50 can be accessed by using either the name xyz or the address 1380.
Pointer Declaration
A pointer is just a C variable whose value is the address of another variable!
After declaring a pointer:
int *ptr;
ptr doesn’t actually point to anything yet.
We can either:
• Make it point to some existing variable (which is in the stack), or
• Dynamically allocate memory (in the heap) and make it point to it
Declaration
Pointer variables must be declared before we use them.
General form:
data_type *pointer_name;
Three things are specified in the above declaration:
• The asterisk (*) tells that the variable pointer_name is a pointer variable.
• pointer_name needs a memory location.
• pointer_name points to a variable of type data_type.
Illegal usage
Example:
int *count;
float *speed;
Once a pointer variable has been declared, it can be made to point to a variable using an
assignment statement like:
int *p, xyz;
:
p = &xyz;
• This is called pointer initialization.
Types of Pointers
Pointer variables must always point to a data item of the same type.
float x;
int *p;
p = &x; // This is an erroneous assignment
Assigning an absolute address to a pointer variable is prohibited.
int *count;
count = 1268;
‘&’ operator
The address of a variable can be determined using the ‘&’ operator.
• The operator ‘&’ immediately preceding a variable returns the address of the variable.
Example:
p = &xyz;
• The address of xyz (1380) is assigned to p.
The ‘&’ operator can be used only with a simple variable or an array element.
&distance
&x[0]
&x[i-2]
Pointer definition
int xyz = 50;
int *ptr; // Here ptr is a pointer to an integer
ptr = &xyz;
Since memory addresses are simply numbers, they can be assigned to some variables
which can be stored in memory.
• Such variables that hold memory addresses are called pointers.
• Since a pointer is a variable, its value is also stored in some memory location.
How it works!!
int a=10, b=5;
int *x, *y; a: 1054 10 42 42
x= &a; y=&b;
*x= 40;
b: 1058 5 45 45
*y= *x + 3;
y= x;
x: 2074 1054 1054 1054