1 ICS 2175 Lecture 6 Pointers
1 ICS 2175 Lecture 6 Pointers
Pointers in C
Pointers: Introduction
A pointer is a variable that represents the location (rather than the
value) of a data items, such as an integer variable or an array
element.
ad d res s o f d em o v alu e o f d em o
p d em o d em o
main()
{
char c = 'Q';
char *char_pointer = &c;
printf("%c %c\n", c, *char_pointer);
c = 'Z';
printf("%c %c\n", c, *char_pointer);
*char_pointer = 'Y';
/* assigns Y as the contents of the memory address specified by
char_pointer */
printf("%c %c\n", c, *char_pointer);
}
Pointers Example 2
#include <stdio.h>
main()
{
int count = 10, x, *int_pointer;
/* this assigns the memory address of count to
int_pointer */
int_pointer = &count;
/* assigns the value stored at the address specified by
int_pointer to x */
x = *int_pointer;
printf("count = %d, x = %d\n", count, x);
}
Pointers: unary operators
A unary operation is an operation with only one operand
(i.e. an operation with a single input).
logical negation, squaring and factorial, n! are examples
of unary operators.
main()
{
int demo=1, var=2;
printf("Before calling functvalue:\tdemo = %d\tvar = %d\n", demo,
var);
functvalue(demo, var);
printf("After calling functvalue:\tdemo = %d\tvar = %d\n", demo, var);
printf("Before calling functref:\tdemo = %d\tvar = %d\n", demo, var);
functref(&demo, &var);
printf("After calling functref:\tdemo = %d\tvar = %d\n", demo, var);
}
Example 3 continued
void functvalue(int demo, int var)
{
demo=0;
var=0;
printf("Within functvalue:\tdemo = %d\tvar = %d\n", demo, var);
}
main()
{
static long int demo[10] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
int loop;
Example
– int* iptr =
(int*) malloc(sizeof(int));
free(iptr);
Caveat: don’t free the same memory block twice!
Malloc
More about pointers visit
http://10.2.20.70/Courses/Common/pointers.pdf
http://pweb.netcom.com/~tjensen/ptr/cpoint.htm