0% found this document useful (0 votes)
19 views

1 ICS 2175 Lecture 6 Pointers

Uploaded by

fasteluv19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

1 ICS 2175 Lecture 6 Pointers

Uploaded by

fasteluv19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 27

ICS 2175: Programming

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.

 Pointers provide a way to return multiple data items from a function


via function arguments.

 They are also closely related to arrays and therefore provide an


alternate way to access individual array elements.
Pointers Fundamentals
 Suppose ‘demo’ is a variable that represents some
particular data item. The compiler will automatically assign
memory cells for this data item depending on its type.
 The data item can then be accessed if we know the
location (address) of the first memory cell.

 The address of v’s memory location can be determined by


the expression &v where & is a unary operator called the
address operator, that evaluates the address of its
operand.
Pointers and addresses
 Thus, using the assignment
pdemo = &demo
pdemo is called a pointer to demo, since it ‘points’ to the
location where demo is stored in memory. I.e. it represents
demo’s address.

ad d res s o f d em o v alu e o f d em o

p d em o d em o

R elatio n s h ip b etw een p d em o an d d em o


(w h ere p d em o = & d em o an d d em o = * p d em o )
Indirection operator
 The data item represented by demo can be accessed by
the expression *pdemo, where * is a unary operator,
called the indirection operator, that operates only on a
pointer variable.

 Therefore, *pdemo and demo both represent the same


data item (contents of demo).

 If pdemo = &demo and vdemo = *pdemo then demo and


vdemo will both represent the same value.
Pointer declarations
 When a pointer variable is declared, the variable name
must be preceded by an asterik (*). 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 stored in the
address represented by the pointer, rather than the
pointer itself.

 Thus, a pointer declaration may be written in general


terms as
<data-type> *ptvar;
Pointers Example 1
#include <stdio.h>

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.

 Unary operators are used in programming languages.


E.g., in the C family of languages, the following operators
are unary:
–Increment: ++x, x++ –Positive: +x
–Decrement: --x, x-- –Negative: -x
–Address: &x One's complement: ~x
–Indirection: *x –Logical negation: !x
–Sizeof: sizeof x
–Sizeof: sizeof(type-name)
Pointers: & and * unary operators
 The unary operators & and * are members of the same
precedence group as the other unary operators.

 This group of operators has a higher precedence than the


groups containing the arithmetic operators,

 The address operator (&) must act upon operands that


are associated with unique addresses, such as ordinary
variables or single array elements.

 The indirection operator (*) can only act upon operands


that are pointers.
Pointer types
 Pointer variables can point to numeric or character
variables, arrays, functions or other pointer variables.

 Also, a pointer variable can be assigned the value of


another pointer variable provided both pointer variables
point to data items of the same type.

 A pointer variable can be assigned a null.


Pointer initialization
 In general it does not make sense to assign an integer
value to a pointer variable.

 An exception, however is an assignment of 0, which is


sometimes used to indicate some special condition.

 In such situations, the recommended programming


practice is to define a symbolic constant NULL which
represents 0, and to use null in the pointer initialization.
Passing pointers to functions
 Pointers are often passed to functions as arguments.

 This allows data items within the calling portion of the


program to be accessed by a function, altered within the
function, and then returned to the calling portion of the
program in altered form.

 We refer to this use of pointers as passing arguments by


reference, in contrast to passing arguments by value.
Pointers: Reference Vs. Value
 When an argument is passed by value, the data item is
copied to the function.
– Thus, any alteration made to the data item within the
function is not carried over into the calling routine.

 When an argument is passed by reference however, the


address of a data item is passed to the function.
– The contents of that address can be accessed freely, either
within the function or within the calling routine. Moreover, any
change that is made to the data item will be recognized in both
the function and the calling routine.
– Thus the use of a pointer as a function argument permits the
corresponding data item to be altered globally from within the
function.
Pointers: Example 3
#include <stdio.h>

void functvalue(int demo, int var);


void functref(int *pdemo, int *pvar);

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);
}

void functref(int *pdemo, int *pvar)


{
*pdemo=0;
*pvar=0;
printf("Within functref:\t*pdemo = %d\t*pvar = %d\n", *pdemo,
*pvar);
}
Pointers and arrays
 An array name is really a pointer to the first element in
the array.

 Therefore if demo is a one dimensional array, then the


address of the first array element can be expressed as
either &demo[0] or simply as demo.

 Moreover, the address of the second element can be


written as either &demo[1] or as (demo + 1), the address
of the third as (demo + 2)….(demo + i).
Pointer arithmetic
 In the expression (demo + i), demo represents an
address, whereas i represents an integer quantity.

 Thus, we are not simply adding numerical values, but we


are specifying an address that is a certain number of
memory cells beyond the address of the first array
element.

 Since &demo[i] and (demo + i) represent the address of


the ith element of demo, then demo[i] and *(demo + i)
represent the contents of that address.
Pointer arithmetic
 Suppose that pdemo is a pointer variable that represents
the address of some variable demo.
– We can write expressions such as ++pdemo, (pdemo-
3), (pdemo+i) where i is an integer etc.
– Each expression will represent an address that is
located some distance from the original address
represented by pdemo.

 The exact distance will be the product of the integer


quantity (i) and the number of bytes or words associated
with the type of the data item to which pdemo points.
Permissible pointer operations
 A pointer variable can be assigned the address of an ordinary
variable (e.g. pdemo = &demo)

 A pointer variable can be assigned the value of another pointer


variable (e.g. pdemo=pvar) provided both pointers point to objects of
the same data type.

 A pointer variable can be assigned a null value.

 An integer quantity can be added to or subtracted from a pointer


variable.

 One pointer variable can be added to or subtracted from another


provided both pointers point to elements of the same array.

 Two pointer variables can be compared provided both pointers point


to objects of the same data type.
Example 4
#include <stdio.h>

main()
{
static long int demo[10] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
int loop;

for(loop=0; loop<=9; loop++)


{
/*Display an array element*/
printf("\nloop=%d\tdemo[loop]=%d\t*(demo+loop)=%d", loop,
demo[loop], *(demo+loop));
/*Display the corresponding array address*/
printf("\t&demo[loop]=%X\tdemo+loop=%X", &demo[loop],
(demo+loop));
}
}
Dynamic memory allocation
 Since an array name is actually a pointer to the first element within
the array, it should be possible to define the array as a pointer
variable rather than as a conventional array.

 A conventional array definition results in a fixed block of memory


being reserved at the beginning of program execution, whereas this
does not occur if the array is represented in terms of a pointer
variable.

 Therefore the use of a pointer variable to represent an array


requires some type of initial memory assignment before the array
elements are processed. This is known as dynamic memory
allocation.
*demo Vs. demo[10]
 Suppose demo is a one-dimensional, 10-element array of
integers.
 It is possible to define demo as a pointer variable rather
than an array. Thus we can write
int *demo rather than int demo[10]

 However, demo is not automatically assigned a memory


block when it is defined as a pointer variable, though a
block of memory large enough to store 10 integer
quantities will be reserved in advance when demo is
defined as an array.
Dynamic Memory
 Comparisons: Java manages memory for you, C does
not
– C requires the programmer to explicitly
allocate and deallocate memory

– Unknown amounts of memory can be


allocated dynamically during run-time with
malloc() and deallocated using free()
Dynamic Memory: Malloc
 Allocates memory in the heap
– Lives between function invocations
 Example
– Allocate an integer
• int* iptr =
(int*) malloc(sizeof(int));
– Allocate a structure
• struct name* nameptr = (struct name*)
malloc(sizeof(struct name));
Dynamic Memory:Free
 Deallocates memory in heap.

 Pass in a pointer that was returned by malloc.

 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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy